-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
69 lines (57 loc) · 1.09 KB
/
stack.c
File metadata and controls
69 lines (57 loc) · 1.09 KB
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
69
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node * next;
} Node;
Node * newNode(int value) {
Node * n = (Node*)malloc(sizeof(Node));
n->next = NULL;
n->value = value;
return n;
}
typedef struct Stack {
Node * top;
} Stack;
Stack * newStack() {
Stack * s = (Stack *)malloc(sizeof(Stack));
s->top = NULL;
}
int isEmpty(Stack * s) {
return s->top == NULL;
}
void push(Stack * s, int value) {
Node * n = newNode(value);
n->next = s->top;
s->top = n;
}
int pop(Stack * s) {
if(isEmpty(s))
exit(2);
Node * n = s->top;
int value = n->value;
s->top = s->top->next;
free(n);
return value;
}
void printStack(Stack * s) {
Node * n = s->top;
printf("[");
while(n != NULL) {
printf(" %d ", n->value);
n = n->next;
}
printf("]\n");
}
int main() {
Stack * s = newStack();
for(int i=0; i<6; i++) {
push(s, rand()%10);
printStack(s);
}
for(int i=0; i<6; i++) {
printStack(s);
pop(s);
}
return 0;
}