-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathstack.c
More file actions
73 lines (61 loc) · 1.62 KB
/
stack.c
File metadata and controls
73 lines (61 loc) · 1.62 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
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
typedef struct stack {
int topIdx;
int capacity;
int *data;
} STACK, *pSTACK;
pSTACK createStack(int capacity) {
pSTACK newStack = (pSTACK) malloc (sizeof(STACK));
if(newStack == NULL) {
printf("ERROR: cannot allocate memeory for stack\n");
exit(EXIT_FAILURE);
}
newStack->data = (int *) malloc (capacity * sizeof(int));
if(newStack->data == NULL) {
printf("ERROR: cannot allocate memeory for stack data\n");
exit(EXIT_FAILURE);
}
newStack->topIdx = -1;
newStack->capacity = capacity;
return newStack;
}
int isFull(pSTACK curStack) {
return curStack->topIdx >= curStack->capacity - 1;
}
int isEmpty(pSTACK curStack) {
return curStack->topIdx == -1;
}
void push(pSTACK curStack, int data) {
if(isFull(curStack)){
return;
}
curStack->data[++(curStack->topIdx)] = data;
printf("%d pushed to stack\n", data);
}
int pop(pSTACK curStack) {
if (isEmpty(curStack)){
printf("stack is empty\n");
return INT_MIN;
}
return curStack->data[(curStack->topIdx)--];
}
int top(pSTACK curStack) {
if (isEmpty(curStack)){
printf("stack is empty\n");
return INT_MIN;
}
return curStack->data[curStack->topIdx];
}
int main() {
pSTACK myStack = createStack(10);
push(myStack, 10);
push(myStack, 20);
push(myStack, 30);
printf("cur top %d\n", top(myStack));
printf("popped element %d\n", pop(myStack));
printf("popped element %d\n", pop(myStack));
printf("popped element %d\n", pop(myStack));
return 0;
}