-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_mod.c
More file actions
99 lines (85 loc) · 1.78 KB
/
stack_mod.c
File metadata and controls
99 lines (85 loc) · 1.78 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include "stack_mod.h"
/**
* A stack.
*
* Pop, push, peek, and maybe is_empty.
*
* Resize as necessary (define initial size of stack? yes if it's an
* array, but no if you're dynamically allocating memory, which is probably
* what you should do - so a singly linked list).
*/
Stack * create_stack(void) {
Stack *stack = (Stack *) malloc(sizeof(Stack));
stack->head = NULL;
stack->next = NULL;
return stack;
}
BOOL is_empty(Stack *stack) {
if (size(stack) > 0) {
return FALSE;
}
return TRUE;
}
int size(Stack *stack) {
int count = 0;
Node *ptr = stack->next;
while (ptr != NULL) {
ptr = ptr->next;
count++;
}
return count;
}
void push(Stack *stack, void* value) {
Node *node = (Node *) malloc(sizeof(Node));
node->value = (int)value;
node->next = NULL;
if (stack->head == NULL) {
stack->next = node;
} else {
stack->head->next = node;
}
stack->head = node;
}
Stack * pop(Stack *stack) {
Node *node = stack->head;
if (1 == size(stack)) {
stack->next = NULL;
stack->head = NULL;
} else if (stack->next != NULL) {
Node *ptr = stack->next;
while (ptr->next->next != NULL) {
ptr = ptr->next;
}
stack->head = ptr;
stack->head->next = NULL;
}
return stack;
}
int peek(Stack *stack) {
if (0 < size(stack)) {
return stack->head->value;
}
return 0;
}
void print_stack(Stack *stack) {
Node *ptr = stack->next;
for (int i = 0; i < size(stack); i++) {
printf("%d", ptr->value);
if (i < (size(stack) - 1)) {
printf(", ");
}
ptr = ptr->next;
}
printf("\n");
}
void destroy_stack(Stack *stack) {
Node *ptr = stack->next;
while (ptr != NULL) {
stack->next = ptr->next;
free(ptr);
ptr = stack->next;
}
free(stack);
}