-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
63 lines (51 loc) · 1.14 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
#include <stdio.h>
#include <stdlib.h>
// This is so so so not a safe stack
// Quick proof of concept. Refactor later.
typedef struct Item
{
int value;
struct Item * prev_item;
} Item;
typedef struct Stack
{
Item * top;
} Stack;
Stack * create_stack()
{
Stack * stack = malloc ( sizeof ( Stack ));
stack->top = NULL;
return stack;
}
Item * create_item( int value, Item * prev_item )
{
Item * item = malloc ( sizeof ( Item ));
item->value = value;
item->prev_item = prev_item;
return item;
}
void add_item_to_stack( Stack * stack, int value)
{
Item * item = create_item( value, stack->top );
stack->top = item;
}
int pop_stack ( Stack * stack )
{
Item * top_item = stack->top;
int ret_val = top_item->value;
stack->top = top_item->prev_item;
free(top_item);
return ret_val;
}
int main(int argc, char *argv[])
{
Stack * s = create_stack();
add_item_to_stack( s, 1 );
add_item_to_stack( s, 3 );
int top_val = pop_stack ( s );
printf("Top value on the stack is: %d\n", top_val);
top_val = pop_stack ( s );
top_val = pop_stack ( s );
printf("The second value on the stack is: %d\n", top_val);
return 0;
}