-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack Operations in C.c
executable file
·121 lines (89 loc) · 2.04 KB
/
Stack Operations in C.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
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
} node;
typedef struct Pop_Node
{
int data;
int returned;
} pop_node;
int push(node *stack, int data)
{
node *temp=(node*)malloc(sizeof(node));
temp->data=data;
temp->next=stack->next;
stack->next=temp;
return stack->next->data;
}
pop_node* pop(node *stack)
{
pop_node *res=(pop_node*)malloc(sizeof(pop_node));
res->returned=0;
node *temp;
if(stack->next == NULL)
{
return res;
}
temp=stack->next;
res->data=stack->next->data;
res->returned=1;
stack->next=stack->next->next;
free(temp);
return res;
}
void display(node *stack)
{
printf("\nDisplay of the Stack\n");
if(stack->next == NULL)
{
printf("The Stack is empty\n");
return;
}
while(stack->next != NULL)
{
printf("%d", stack->next->data);
if(stack->next->next != NULL)
{
printf(" <= ");
}
stack=stack->next;
}
printf("\n");
}
int main()
{
int n, i, data, pushed;
node *stack=(node*)malloc(sizeof(node));
stack->next=NULL;
printf("Enter the initial size of the Stack: ");
scanf("%d", &n);
printf("\nPush %d data to the Stack: \n", n);
for(i=0; i<n; i++)
{
scanf("%d", &data);
pushed=push(stack, data);
printf("%d pushed to the Stack\n", pushed);
}
display(stack);
printf("\nPopping data from the Stack: ");
pop_node *popped;
popped=pop(stack);
if(popped->returned == 1)
{
printf("\n%d popped from the Stack\n", popped->data);
}
else
{
printf("\nNothing to pop, the Stack is empty\n");
}
display(stack);
printf("\nPush data to the Stack: ");
scanf("%d", &data);
pushed=push(stack, data);
printf("%d pushed to the Stack\n", pushed);
display(stack);
return 0;
}