-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.cpp
76 lines (66 loc) · 1.26 KB
/
Stack.cpp
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node{
int data;
Node *next;
};
struct Stack{
Node *top;
int num_of_data ;
};
void Push(Stack *st, int data);
void Pop(Stack *st);
int main(){
int n,m;
char arr[15];
Stack st;
st.top = NULL;
st.num_of_data = 0;
scanf("%d", &n);
while(getchar() != '\n');
for(int i = 0; i < n; i++){
gets(arr);
if(!strncmp(arr,"size",4)){
printf("%d\n", st.num_of_data);
}
else if(!strncmp(arr, "pop", 3)){
Pop(&st);
}
else if(!strncmp(arr,"empty", 5)){
if(st.num_of_data == 0)
printf("%d\n", 1);
else
printf("%d\n", 0);
}
else if(!strncmp(arr, "top", 3)){
if(st.num_of_data == 0){
printf("%d\n", -1);
continue;
}
printf("%d\n", st.top->data);
}
else{
m = atoi(&arr[5]); Push(&st,m);
}
}
}
void Push(Stack *st, int data){
Node *newnode;
newnode = (Node *)malloc(sizeof(Node));
newnode->data = data; newnode->next = st->top;
st->top = newnode;
st->num_of_data +=1;
}
void Pop(Stack *st){
if(st->num_of_data == 0){
printf("-1\n");
return;
}
Node *tmp;
tmp = st->top;
printf("%d\n", tmp->data);
st->top = st->top->next;
free(tmp);
st->num_of_data -= 1;
}