-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackLinkedlist.c
97 lines (97 loc) · 1.72 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
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int data;
struct stack *next;
};
struct stack *top = 0, *ptr, *newnode;
struct stack *push(struct stack *top);
struct stack *pop(struct stack *top);
void peek(struct stack *top);
void display(struct stack *top);
int main()
{
int option;
printf("Choose from menu\n");
printf("1.push\n");
printf("2.pop\n");
printf("3.peek\n");
printf("4.display\n");
while (1)
{
printf("Choose option\n");
scanf("%d", &option);
switch (option)
{
case 1:
top = push(top);
break;
case 2:
top = pop(top);
break;
case 3:
peek(top);
break;
case 4:
display(top);
break;
default:
exit(1);
}
}
return 0;
}
struct stack *push(struct stack *top)
{
int data;
newnode = (struct stack *)malloc(sizeof(struct stack));
printf("Enter data\n");
scanf("%d", &newnode->data);
if (top == 0)
{
newnode->next = 0;
ptr = top = newnode;
}
else
{
newnode->next = top;
top = newnode;
}
return top;
}
struct stack *pop(struct stack *top)
{
if (top == 0)
{
printf("Stack Underflow\n");
}
else
{
ptr = top;
top = top->next;
free(ptr);
}
return top;
}
void peek(struct stack *top)
{
printf("%d\n", top->data);
}
void display(struct stack *top)
{
ptr = top;
if (top == 0)
{
printf("Stack is Empty\n");
}
else
{
while (ptr != 0)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
}