-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
63 lines (58 loc) · 1.57 KB
/
Copy pathstack.c
File metadata and controls
63 lines (58 loc) · 1.57 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
/* Jacobus Burger (2025-08-11)
* Stack (C99)
* Description:
* Stacks are a First In Last Out (FILO) data structure where you can
* `push` items to the top, or `pop` items from the top, like adding
* and removing sheets of paper from the top of a stack of paper.
* Info:
* - https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
*/
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
/* There are many ways to dynamically handle stack size, that could be
* done using a linked list, a dynamic array, or other data
* structures under the hood. Implementation details are left to
* the programmer to decide what tradeoffs to make.
*/
#define LEN 10
/* Stack Abstract Data Type (ADT)
* size_t head: top of stack index (and size of stack)
* int data[LEN]: array of data (static data for now)
*/
typedef struct {
size_t head;
int data[LEN]; // this can also be done with a dynamic array
} stack_t;
/* Time Complexity: O(1)
* Space Complexity: O(1)
*/
void push(stack_t *s, int value)
{
if (s->head + 1 >= LEN)
return;
s->data[s->head] = value;
s->head++;
}
/* Time Complexity: O(1)
* Space Complexity: O(1)
*/
int pop(stack_t *s)
{
if (s->head <= 0)
return -1;
s->head--;
int value = s->data[s->head];
return value;
}
int main(void)
{
stack_t s;
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("%i\n", pop(&s));
printf("%i\n", pop(&s));
printf("%i\n", pop(&s));
printf("%i\n", pop(&s));
}