-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc_stack.c
56 lines (47 loc) · 909 Bytes
/
c_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
#include "c_stack.h"
#include <assert.h>
#include <stdlib.h>
stack_node* create_node(int payload)
{
stack_node* node = calloc(sizeof(stack_node),1);
node->payload = payload;
return node;
}
void reap_node(stack_node**node)
{
if (*node == NULL)
return;
free(*node);
*node = NULL;
}
bool stack_empty(stack_node* head)
{
return head == NULL;
}
void stack_push(int value, stack_node** head)
{
stack_node* new_node = create_node(value);
new_node->next = *head;
*head = new_node;
return;
}
int stack_pop(stack_node** head)
{
assert(head != NULL);
assert(*head != NULL);
int value = (*head)->payload;
stack_node* next_node = (*head)->next;
reap_node(head);
*head = next_node;
return value;
}
int stack_peek(stack_node* head)
{
assert(head != NULL);
return head->payload;
}
void stack_clear(stack_node **head)
{
while (!stack_empty(*head))
stack_pop(head);
}