forked from mckennapsean/code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.c
50 lines (39 loc) · 866 Bytes
/
stack.c
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
// inspired by Leon Tabak
// implementation of a stack
#include <stdio.h>
#include <stdlib.h>
struct node{
int val;
struct node* next;
};
typedef struct node Node;
typedef struct node* NodePointer;
NodePointer top = NULL;
// test if the stack is empty
int isEmpty() {
return top == NULL;
}
// add a number to the stack
void push(int num){
NodePointer np = (NodePointer) malloc(sizeof(Node));
np->val = num;
np->next = top;
top = np;
}
// test the stack implementation
void main(){
// is the stack empty?
printf("Is stack empty? %d\n", isEmpty());
// add some numbers to the stack
push(1);
push(2);
push(3);
// now see if the stack is empty?
printf("Is stack empty? %d\n", isEmpty());
// and then print off the stack
NodePointer np = top;
while(np != NULL){
printf("%d\n", np->val);
np = np->next;
}
}