forked from amritanand-py/cps02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathM 102 - Stacks Using a Linked List.c
68 lines (64 loc) · 1.42 KB
/
M 102 - Stacks Using a 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
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "math.h"
//BODY
int stackArr[100005];
int top = -1;// - Stores the index of the topmost element on the stack
void push(int x){
top++;
stackArr[top]=x;
} //- Insert an element onto the top of the stack
int peek(){
return stackArr[top];
} //- Returns the topmost element on the stack
void pop(){
stackArr[top]=NULL;
top--;
} //- Removes an element from the top of the stack
int empty(){
if(top==-1)
return 1;
else
return 0;
}// - Returns 1 if the stack is empty and 0 otherwise
//TAIL
int main()
{
int n;
top = -1;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int t, x;
scanf("%d", &t);
if (t == 1) {
scanf("%d", &x);
push(x);
}
else if (t == 2) {
if (empty()) {
printf("Invalid\n");
}
else {
pop();
}
}
else if (t == 3){
if (empty()) {
printf("Invalid\n");
continue;
}
for (int j = top; j >= 0; j--) {
printf("%d ", stackArr[j]);
}printf("\n");
}
else {
if (empty()) {
printf("Invalid\n");
continue;
}
printf("%d\n", peek());
}
}
return 0;
}