-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
142 lines (107 loc) · 2.02 KB
/
stack.c
File metadata and controls
142 lines (107 loc) · 2.02 KB
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
#include <stdio.h>
#include <malloc.h>
#define CREATE_NEW_NODE (node*)malloc(sizeof(node))
typedef struct Node node;
struct Node{
int num;
node *next;
};
node *initStack(node*, int);
node *pushStack(node*, int);
node *popStack(node*);
void printStack(node*);
void freeStack(node*);
int main(void){
int addnum = 0;
int nMenu = 0;
node *front = 0;
while (nMenu != 4){
printf("1.Push 2.Pop 3.Print 4.Exit : ");
scanf("%d", &nMenu);
switch (nMenu)
{
case 1:
printf("enter number : ");
scanf("%d", &addnum);
// empty stack
if (front == NULL){
front = initStack(front, addnum);
}
// not empty stack
else{
front = pushStack(front, addnum);
}
break;
case 2:
// empty stack
if (front == NULL){
printf("empty stack already\n");
}
// not empty stack
else{
front = popStack(front);
}
break;
case 3:
// empty stack
if (front == NULL){
printf("empty stack\n");
}
// not empty stack
else{
printStack(front);
}
break;
default:
break;
}
}
freeStack(front);
return 0;
}
node *initStack(node* front, int addnum){
front = CREATE_NEW_NODE;
front->next = NULL;
front->num = addnum;
}
node *pushStack(node* front, int addnum){
node *temp;
temp = CREATE_NEW_NODE;
temp->next = front;
temp->num = addnum;
front = temp;
return front;
}
node *popStack(node* front){
node *temp;
temp = front;
// front == rear
if (front->next == NULL){
front = 0;
printf("empty stack now\n");
}
// front != rear
else{
front = front->next;
}
free(temp);
return front;
}
void printStack(node* front){
node *temp;
temp = front;
while (temp != NULL){
printf("%d\n", temp->num);
temp = temp->next;
}
}
void freeStack(node* front){
node *temp_front;
node *temp;
temp_front = front;
while (temp_front != NULL){
temp = temp_front;
temp_front = temp_front->next;
free(temp);
}
}