-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackWithLinkedList.c
137 lines (122 loc) · 2.16 KB
/
StackWithLinkedList.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *link;
};
struct Node *Top = NULL;
struct Node *CreateNode()
{
struct Node *newNode;
newNode = (struct Node *)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Allocation Failed\n");
}
else
{
printf("Node Created\n");
return newNode;
}
}
void push(int key)
{
struct Node *newNode = CreateNode();
newNode->data = key;
newNode->link = NULL;
if (Top == NULL)
{
Top = newNode;
}
else
{
newNode->link = Top;
Top = newNode;
}
}
int pop()
{
if (Top == NULL)
{
return -1;
}
else
{
int key;
struct Node *temp;
temp = Top;
Top = temp->link;
key = temp->data;
free(temp);
return key;
}
}
int peek()
{
if (Top == NULL)
{
return -1;
}
else
{
int key;
key = Top->data;
return key;
}
}
int main()
{
while (1)
{
printf("\n");
printf("Enter 1 to push in stack\n");
printf("Enter 2 to pop in stack\n");
printf("Enter 3 to peek in stack\n");
printf("Enter 4 to Exit\n");
int ch;
scanf("%d", &ch);
printf("\n");
switch (ch)
{
case 1:
{
int element;
printf("\nEnter the Element to Push : ");
scanf("%d", &element);
push(element);
break;
}
case 2:
{
int key = pop();
if(key==-1)
{
printf("\nStack is Empty\n");
}
else
printf("\n%d is pop from the stack.\n", key);
break;
}
case 3:
{
int key = peek();
if(key==-1)
{
printf("\n Stack is Empty\n");
}
else
printf("\nTop of Stack is : %d\n", key);
break;
}
case 4:
{
exit(1);
break;
}
default:
break;
}
}
return 0;
}