-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstacks.c
More file actions
52 lines (44 loc) · 939 Bytes
/
stacks.c
File metadata and controls
52 lines (44 loc) · 939 Bytes
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
#include <stdlib.h>
#include "stacks.h"
struct _element {
Item* item;
struct _element* next;
};
struct _stack {
Element* top;
};
Stack* CreateStack() {
Stack* stack = (Stack*) malloc(sizeof(Stack));
stack->top = NULL;
return stack;
}
void Push(Stack* stack, Item* item) {
if (stack == NULL) return;
Element* element = (Element*) malloc(sizeof(Element));
Element* buffer = stack->top;
stack->top = element;
stack->top->next = buffer;
stack->top->item = item;
}
Item* Pop(Stack* stack) {
if (IsStackEmpty(stack)) return NULL;
Element* top = stack->top;
Item* item = top->item;
stack->top = stack->top->next;
free(top);
return item;
}
void ClearStack(Stack* stack) {
while (Pop(stack) != NULL);
}
int IsStackEmpty(Stack* stack) {
return (stack->top == NULL);
}
int IsInStack(Stack* stack, Item* item) {
Element* e = stack->top;
while (e != NULL) {
if (item == e->item) return 1;
e = e->next;
}
return 0;
}