forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackImplementationWithLinkedList.c
143 lines (129 loc) · 2.33 KB
/
StackImplementationWithLinkedList.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
138
139
140
141
142
143
/*
A stack is an Abstract Data Type (ADT), commonly used in most programming languages.This feature makes it LIFO data structure.
LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first.
The Basic operation in Stack are:
1.push() − Pushing (storing) an element on the stack.
2.pop() − Removing (accessing) an element from the stack.
3.peek() − get the top data element of the stack, without removing it.
4.display() - used to display the elements
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *top = NULL;
void push();
void pop();
void display();
void push()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("\n Enter node data:");
scanf("%d", &temp->data);
temp->link = top;
top = temp;
}
void pop()
{
struct node *temp;
if (top == NULL)
printf("No element");
else
{
temp = top;
printf("The deleted element is %d", temp->data);
top = top->link;
temp->link = NULL;
free(temp);
}
}
void display()
{
struct node *temp;
if (top == NULL)
printf("\n Stack is empty");
else
{
temp = top;
printf("\nData is");
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->link;
}
}
}
void main()
{
int choice;
do
{
printf("\n*****Menu*****\n");
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("Enter your choice:");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Invalid choice");
}
}
while (choice < 5);
getchar();
}
/*
*****MENU******
1.Push
2.Pop
3.Display
4.Exit
Enter your choice 1
Enter node data 23
*****MENU******
1.Push
2.Pop
3.Display
4.Exit
Enter your choice 1
Enter node data 24
*****MENU******
1.Push
2.Pop
3.Display
4.Exit
Enter your choice 2
The deleted element is 24
*****MENU******
1.Push
2.Pop
3.Display
4.Exit
Enter your choice
1
Enter node data 25
*****MENU******
1.Push
2.Pop
3.Display
4.Exit
Enter your choice 3
Data is 23 25
Time complexity : O(1)
Space Complexity: O(n)
*/