-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathStack using linked list.c
106 lines (94 loc) · 1.84 KB
/
Stack using linked list.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>
struct Node
{
int data;
struct Node *next;
};
struct Node *head = NULL;
void push(int value)
{
struct Node *n = (struct Node *)malloc(sizeof(struct Node *));
if (head == NULL)
{
head = n;
n->data = value;
n->next = NULL;
return;
}
n->next = head;
n->data = value;
head = n;
}
void pop()
{
struct Node *temp = head;
if (head == NULL)
{
printf("\nStack is empty.\n");
return;
}
head = head->next;
temp->next = NULL;
}
void peek()
{
if (head == NULL)
{
printf("\nStack is empty.\n");
return;
}
printf("The top element is: %d\n", head->data);
}
void display()
{
struct Node *temp = head;
if (head == NULL)
{
printf("\nStack is empty.\n");
return;
}
printf("\nElements of stack are:\n");
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
}
int main()
{
while (1)
{
printf("\n=======Menu=======\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n\n");
int c, n;
scanf("%d", &c);
switch (c)
{
case 1:
printf("Enter the element to be inserted: ");
scanf("%d", &n);
push(n);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
default:
printf("Please select a valid option.");
}
}
return 0;
}