-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackLL.c
106 lines (97 loc) · 1.62 KB
/
stackLL.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
struct LL
{
int data;
struct LL *next;
};
struct stack
{
struct LL *top;
};
struct stack *createStack()
{
struct stack *stk;
stk=malloc(sizeof(struct stack));
stk->top=NULL;
return stk;
}
void push(struct stack *stk, int data)
{
struct LL *temp;
temp=malloc(sizeof(struct LL));
if(!temp)
{
printf ("Stack Overflow\n");
return ;
}
temp->data=data;
temp->next=stk->top;
stk->top=temp;
}
int isEmpty(struct stack *stk)
{
return (stk->top==NULL);
}
int size(struct stack*stk)
{
int count=0;
struct LL *temp;
if(isEmpty(stk))
return 0;
temp=stk->top;
while(temp)
{
count++;
temp=temp->next;
}
return count;
}
int pop(struct stack *stk)
{
int data;
struct LL *temp;
if(isEmpty(stk))
return INT_MIN;
temp=stk->top;
stk->top=stk->top->next;
data=temp->data;
free(temp);
return data;
}
int peek(struct stack *stk)
{
if(isEmpty(stk))
return INT_MIN;
return stk->top->data;
}
void delete(struct stack *stk)
{
struct LL*temp,*p;
p=stk->top;
while(p)
{
temp=p->next;
p=p->next;
free(temp);
}
free(stk);
}
int main ()
{
int i=0;
struct stack *stk=createStack();
for(i=0;i<=10;i++)
push(stk,i);
printf ("Top element is %d\n",peek(stk));
printf ("Stack size is %d\n",size(stk));
for(i=0;i<=10;i++)
printf ("Popped element is %d\n",pop(stk));
if(isEmpty(stk))
printf ("stack is empty");
else
printf("Stack is not empty");
delete(stk);
return 0;
}