/
stack.c
68 lines (52 loc) · 1.27 KB
/
stack.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 <stdlib.h>
#include <stdio.h>
#include "stack.h"
//
// Private functions
//
int numItemsInStack(Stack* stack) {
return stack->pList->length;
}
//
// Functions from header file
//
Stack* createEmptyStack(void) {
Stack* result = malloc(sizeof(Stack));
result->pList = newList();
return result;
}
void freeStack(Stack* stack) {
freeList(stack->pList);
free(stack);
}
void push(Stack* stack, StackVal val) {
addAtHead(stack->pList, (void*) val);
}
StackVal pop(Stack* stack) {
StackVal val;
if (numItemsInStack(stack) <= 0) {
fprintf(stderr, "Attempted to pop from empty stack! Exiting...\n");
exit(-1);
}
val = (StackVal) (stack->pList->pHead->data);
removeAtHead(stack->pList);
return val;
}
StackVal peek(Stack* stack) {
StackVal val;
if (numItemsInStack(stack) <= 0) {
fprintf(stderr, "Attempted to peek from empty stack! Exiting...\n");
exit(-1);
}
return (StackVal) (stack->pList->pHead->data);
}
void printStack(Stack* stack) {
int i;
if (stack->pList->length > 0) {
printf("%d", (int) get(stack->pList, 0)->data);
}
for (i = 1; i < stack->pList->length; i++) {
printf(", %d", (int) get(stack->pList, i)->data);
}
printf("\n");
}