-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.c
More file actions
135 lines (126 loc) · 2.38 KB
/
Copy pathStack.c
File metadata and controls
135 lines (126 loc) · 2.38 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
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
/*
* Stack.c
*
* Created on: May 19, 2016
* Author: Moawiya
*/
#include "Stack.h"
struct _Stack_t {
StackElement head;
StackElement tail;
copyStackData copyFunc;
freeStackData freeFunc;
unsigned int size;
};
struct _StackElement_t {
StackData data;
StackElement next;
};
Stack createStack(copyStackData copyFunc, freeStackData freeFunc) {
if (copyFunc == NULL || freeFunc == NULL) {
return NULL;
}
Stack s = allocate(sizeof(*s));
if (s == NULL) {
return NULL;
}
s->copyFunc = copyFunc;
s->freeFunc = freeFunc;
s->head = NULL;
s->tail = NULL;
s->size = 0;
return s;
}
void destroyStack(Stack s) {
if (s == NULL) {
return;
}
while (s->head != NULL) {
StackElement tmp = s->head;
s->head = s->head->next;
s->freeFunc(tmp->data);
deallocate(tmp, sizeof(*tmp));
//free(tmp);
s->size--;
}
deallocate(s, sizeof(*s));
//free(s);
}
ReturnVal push(StackData elmnt, Stack s) {
if (s == NULL || elmnt == NULL) {
return NullArgument;
}
StackData copy_data = s->copyFunc(elmnt);
if (copy_data == NULL) {
return MemoryError;
}
StackElement new_elmnt = allocate(sizeof(*new_elmnt));
//StackElement new_elmnt = malloc(sizeof(*new_elmnt));
if (new_elmnt == NULL) {
s->freeFunc(copy_data);
return MemoryError;
}
new_elmnt->data = copy_data;
new_elmnt->next = s->head;
s->head = new_elmnt;
if (s->size == 0) {
s->tail = s->head;
}
s->size++;
return Success;
}
ReturnVal pop(Stack s) {
if (s == NULL) {
return NullArgument;
}
if (s->size == 0) {
return NoElements;
}
StackElement tmp = s->head;
s->head = tmp->next;
s->freeFunc(tmp->data);
deallocate(tmp, sizeof(*tmp));
//free(tmp);
s->size--;
if (s->size == 0) {
s->tail = NULL;
}
return Success;
}
ReturnVal top(Stack s, StackData* retrieved) {
if (s == NULL) {
return NullArgument;
}
if (s->size == 0) {
return NoElements;
}
*retrieved = s->copyFunc(s->head->data);
if (*retrieved == NULL) {
return MemoryError;
}
return Success;
}
unsigned int stackSize(Stack s) {
if (s == NULL) {
return 0;
}
return s->size;
}
void printStack(Stack s) {
if (s == NULL || s->size == 0) {
return;
}
char* delim = "|===|";
char* wall = "| |";
StackElement pntr = s->head;
while (pntr != NULL) {
//printf("%s\n", wall);
printf("| %c |\n", *(char*)pntr->data);
if (pntr->next == NULL) {
printf("=====\n");
} else {
printf("%s\n", delim);
}
pntr = pntr->next;
}
}