-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_of_strings.c
More file actions
81 lines (68 loc) · 1.5 KB
/
stack_of_strings.c
File metadata and controls
81 lines (68 loc) · 1.5 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
demonstrates the extra memory handling overhead of strings
*/
typedef char* stackdata;
typedef struct node_ {
stackdata val;
struct node_* next;
} node, * node_ptr;
typedef struct {
node_ptr top;
} stacktype, * stack;
stack initStack() {
stack newnode = malloc(sizeof(stacktype));
newnode->top = NULL;
return newnode;
}
int empty(stack s) {
return s->top == NULL;
}
/* head will thus change so return new head */
void push(stack s, stackdata data) {
node_ptr newnode = malloc(sizeof(node));
newnode->val = malloc(strlen(data)+1);
strcpy(newnode->val, data);
newnode->next = s->top;
s->top = newnode;
}
/* head will thus change so return new head. Note something very bad happens if stack empty
Caller must free string */
stackdata pop(stack s) {
stackdata value;
node_ptr tmp = s->top;
value = tmp->val;
s->top = tmp->next;
free(tmp);
return value;
}
void free_stack(stack s) {
while(!empty(s)) {
pop(s);
}
free(s);
}
void get_data(stack s) {
char data[64];
const char* p = NULL;
printf("Enter a string without spaces, new line to separate. Enter \'quit\' to end entering data\n");
while(fgets(data, sizeof data, stdin)) {
if(strncmp(data, "quit", 4) == 0)
break;
/* TODO - trim string */
push(s, data);
}
}
int main() {
stack s = initStack();
get_data(s);
while(!empty(s)) {
char* tmp = pop(s);
printf("element val=%s\n", tmp);
free(tmp);
}
free_stack(s);
return 0;
}