-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
68 lines (53 loc) · 1.04 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// implementing stack with operations push and pop + basic operations
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int val;
struct node * next;
}node;
void push(node ** top, int n);
int pop(node ** top);
void printStack(node * top);
int main(){
node * top = NULL;
printStack(top);
push(&top, 2);
printStack(top);
push(&top, 1);
printStack(top);
pop(&top);
pop(&top);
printStack(top);
pop(&top);
return(0);
}
int pop(node ** top){
int retval = -1;
if(*top == NULL)
printf("Nothing to pop, go home");
else{
node * temp = *top;
retval = temp->val;
*top = temp->next;
free(temp);
}
return retval;
}
void push(node ** top, int n){
node * newNode = malloc(sizeof(node));
newNode->val = n;
newNode->next = *top;
*top = newNode;
}
void printStack(node * top){
if(top == NULL)
printf("Empty Stack");
else {
node * current = top;
while(current!=NULL){
printf("%d ",current->val);
current = current->next;
}
}
printf("\n");
}