-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
75 lines (73 loc) · 1.55 KB
/
Copy pathstack.c
File metadata and controls
75 lines (73 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
75
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//LIFO
struct Stack {
int *array;
int capacity;
int top;
};
typedef struct Stack Stack;
Stack new_stack(int capacity){
Stack stack;
stack.capacity = capacity;
stack.array = malloc(stack.capacity * sizeof(int));
stack.top = -1;
return stack;
}
bool is_full(Stack stack){
return stack.top == stack.capacity - 1;
}
bool is_empty(Stack stack){
return stack.top == -1;
}
void push(Stack *stack, int data){
if(is_full(*stack)){
printf("Stack Full!\n");
return;
}
stack->top += 1;
stack->array[stack->top] = data;
}
int pop(Stack *stack){
if(is_empty(*stack)){
printf("Stack is empty!\n");
return __INT_MAX__;
}
int ret = stack->array[stack->top];
stack->top -= 1;
return ret;
}
int peek(Stack stack){
if(is_empty(stack)){
printf("Stack is empty!\n");
return __INT_MAX__;
}
int ret = stack.array[stack.top];
return ret;
}
void print_stack(Stack stack){
for(int i = 0; i <= stack.top;i++){
printf("%d,", stack.array[i]);
}
printf("\n");
}
int main(){
Stack stack = new_stack(5);
int c = pop(&stack); // pop from empty stack
push(&stack,0);
push(&stack,1);
push(&stack,2);
push(&stack,3);
push(&stack,4);
print_stack(stack);
push(&stack,5); //stack full;
print_stack(stack);
int p = pop(&stack);
int q = peek(stack);
printf("%d\n", p);
print_stack(stack);
printf("%d\n",q);
print_stack(stack);
return 0;
}