-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
74 lines (71 loc) · 1.55 KB
/
stack.c
File metadata and controls
74 lines (71 loc) · 1.55 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
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct Stack{
int *items;
int top;
int capacity;
} Stack;
void initialize(Stack* stack, int capacity) {
stack->capacity=capacity;
stack->top=-1;
stack->items=(int *)malloc(capacity * sizeof(int));
}
void push(Stack* stack,int value){
if(stack->top==stack->capacity-1){
printf("stack overflow\n");
}
else{
stack->top++;
stack->items[stack->top]=value;
printf("%d\n",stack->items[stack->top]);
}
}
void pop(Stack* stack){
if(stack->top==-1){
printf("stack underflow\n");
}
else{
printf("%d\n",stack->items[stack->top]);
stack->top--;
}
}
void top(Stack* stack){
if(stack->top==-1){
printf("stack underflow\n");
}
else{
printf("%d\n",stack->items[stack->top]);
}
}
void free_(Stack* stack){
free(stack->items);
}
int main() {
int t;
scanf("%d",&t);
while(t--){
int q,n;
scanf("%d %d",&q,&n);
Stack stack;
initialize(&stack,n);
while(q--){
char query[10];
scanf("%s",query);
if(strcmp(query,"push")==0){
int value;
scanf("%d",&value);
push(&stack,value);
}
else if(strcmp(query,"pop")==0){
pop(&stack);
}
else if(strcmp(query,"top")==0){
top(&stack);
}
}
free_(&stack);
}
return 0;
}