-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
62 lines (54 loc) · 1.06 KB
/
stack.c
File metadata and controls
62 lines (54 loc) · 1.06 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
/*
Written by William Sutherland for
COMP20007 Assignment 1 2023 Semester 1
Modified by Grady Fitzpatrick
Implementation for module which contains
stack-related data structures and
functions.
*/
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct stack
{
void *item;
struct stack *below;
};
struct stack *createStack(void *item)
{
struct stack *s = (struct stack *)malloc(sizeof(struct stack));
assert(s);
s->item = item;
s->below = NULL;
return s;
}
void *pop(struct stack **s)
{
if (!s || !*s)
return NULL;
void *item = (*s)->item;
struct stack *b = (*s)->below;
free(*s);
*s = b;
return item;
}
void push(struct stack **s, void *item)
{
if (!s || !*s)
{
*s = createStack(item);
return;
}
struct stack *top = createStack(item);
top->below = *s;
*s = top;
}
void freeStack(struct stack *s)
{
for (struct stack *curr = s; curr != NULL; s = curr)
{
curr = curr->below;
free(s);
}
}