summaryrefslogtreecommitdiff
path: root/queue.c
blob: e0923ecbab6d4224d966afeaaf43f68627994e45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>

struct node {
	int val;
	struct node *next;
};

struct node *head;
struct node *tail;

void
enqueue(int val)
{
	struct node *tmp = malloc(sizeof(struct node));
	tmp->val = val;
	if (head == NULL) {
		tail = head = tmp;
		return;
	}
	tail->next = tmp;
	tail = tmp;
}

int
deque()
{
	if (head == NULL) {
		return -1;
	}
	struct node *tmp = head;
	int val = tmp->val;
	head = head->next;
	free(tmp);
	return val;
}

int
peek()
{
	return head == NULL ? -1 : head->val;
}

void
print()
{
	struct node *cur = head;
	while (cur != NULL) {
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

int
main()
{
	int val, n = 0;
	printf("How many integers?\n");
	scanf("%d", &n);
	for (int i = 0; i < n; ++i) {
		printf("Enter an integer \n");
		scanf("%d", &val);
		enqueue(val);
		print();
	}
	return 0;
}