-
Notifications
You must be signed in to change notification settings - Fork 331
/
stack_usinglist.c
59 lines (53 loc) · 1 KB
/
stack_usinglist.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
#include <stdio.h>
#include <stdlib.h>
struct Stack{
int size;
struct List{
int item;
struct List *next;
} *head;
};
typedef struct Stack *slink;
slink create_stack(void){
slink stack=malloc(sizeof(struct Stack));
if(!stack)
return stack;
stack->size=0;
stack->head=NULL;
return stack;
}
int empty(slink stack){
return stack->size==0;
}
void push_stack(slink stack,int item){
struct List *new=malloc(sizeof(struct List));
if(!new)
return;
new->item=item;
new->next=stack->head;
stack->head=new;
stack->size++;
}
int pop_stack(slink stack){
if(empty(stack))
return -1;
struct List *torm=stack->head;
int retval=stack->head->item;
stack->head=stack->head->next;
free(torm);
stack->size--;
return retval;
}
int main(){
slink stack=create_stack();
int data[]={1,2,3,4,5,6,7,8,9};
int i=0;
while(i<6)
push_stack(stack,data[i++]);
while(!empty(stack))
printf("%d\n",pop_stack(stack) );
while(i<9)
push_stack(stack,data[i++]);
while(!empty(stack))
printf("%d\n",pop_stack(stack) );
}