-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathStackLinkedList.c
119 lines (105 loc) · 2.17 KB
/
StackLinkedList.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *top = NULL;
// Function to push an element onto the stack
void push(int x)
{
struct node *t;
t = (struct node*)malloc(sizeof(struct node));
// Check if memory allocation is successful
if (t == NULL)
printf("Stack is full\n");
else
{
t->data = x;
t->next = top;
top = t;
}
}
// Function to pop an element from the stack
int pop()
{
struct node *t;
int x = -1;
// Check if the stack is empty
if (top == NULL)
printf("Stack is Empty\n");
else
{
t = top;
top = top->next;
x = t->data;
free(t);
}
return x;
}
// Function to display the elements of the stack
void display()
{
struct node *p;
p = top;
// Traverse the stack and print each element
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
int ch;
do
{
// Display menu options
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
{
int x;
// Get the element to be pushed from the user
printf("Enter the element to be pushed: ");
scanf("%d", &x);
push(x);
break;
}
case 2:
{
int x;
// Pop an element and display it
x = pop();
printf("Popped element is: %d\n", x);
break;
}
case 3:
{
// Display the elements in the stack
display();
break;
}
case 4:
{
printf("Exiting...\n");
break;
}
default:
{
printf("Invalid choice\n");
break;
}
}
}
while (ch != 4);
return 0;
}