-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
142 lines (105 loc) · 1.99 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**********************************************
* stack.c - a linked list based stack
*
* Lindsey Bieda
***********************************************/
#include <stdio.h>
#include <malloc.h>
//linked list struct
struct stack
{
struct node *head;
int count;
};
//node struct
struct node
{
int data;
struct node *next;
};
// allocates a new list, inits object
struct stack* stack_new()
{
struct stack* newStack;
newStack = malloc(sizeof(struct stack));
newStack->count = 0;
newStack->head = NULL;
return newStack;
}
// adds in a FILO fashion
void stack_push(struct stack* stacklist, int data)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = stacklist->head;
stacklist->head = newNode;
stacklist->count++;
}
// removes in a FILO fashion
int stack_pop(struct stack* stacklist)
{
int temp = -1;
struct node* tempptr = stacklist->head;
if(stacklist->head == NULL)
{
return temp;
}
stacklist->head = tempptr->next;
temp = tempptr->data;
stacklist->count -= 1;
free(tempptr);
return temp;
}
// clears, and deallocates list
void stack_clear(struct stack* stacklist)
{
struct node* temp;
struct node* cur = stacklist->head;
while(cur)
{
temp = cur;
cur = cur->next;
free(temp);
}
stacklist->count = 0;
stacklist->head = NULL;
}
// deallocates list nodes
void stack_free(struct stack* stacklist)
{
stack_clear(stacklist);
free(stacklist);
}
// returns number of nodes
int stack_count(struct stack* stacklist)
{
return stacklist->count;
}
// prints all the nodes
void stack_print(struct stack* stacklist)
{
struct node* cur = stacklist->head;
if(cur == NULL)
{
printf("Err: Empty stack\n");
return;
}
while(cur)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main()
{
struct stack* myStack = stack_new();
stack_print(myStack);
stack_push(myStack, 1);
stack_push(myStack, 2);
stack_push(myStack, 3);
stack_print(myStack);
stack_pop(myStack);
stack_print(myStack);
return 0;
}