summaryrefslogtreecommitdiff
path: root/stack.c
blob: a460629d34e7771bb2239754be7a4379ff4d0dbd (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
#include <stdio.h>
#include <stdlib.h>

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

struct node *head;

void
push(int val)
{
	struct node *tmp = malloc(sizeof(struct node));
	tmp->val = val;
	tmp->prev = head;
	head = tmp;
}

int
pop()
{
	if (head == NULL) {
		return -1;
	}
	struct node *tmp = head;
	int val = tmp->val;
	head = head->prev;
	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->prev;
	}
	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);
		push(val);
		print();
	}
	return 0;
}