blob: a27869f32bff3d703e7f1911bf22f43304773d6d (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
/* Stack implementation is a linked list with a header */
struct node
{
elem data;
ptr_to_node next;
};
int is_empty(stack s)
{
return s->next == NULL;
}
stack create_stack()
{
stack s;
s = malloc(sizeof(struct node));
if(s == NULL)
printf("error");
make_empty(s);
return s;
}
void make_empty(stack s)
{
if(s == NULL)
printf("must create a stack first");
else
while(!is_empty(s))
pop(s);
}
void push(elem x, stack s)
{
ptr_to_node tmp;
tmp = malloc(sizeof(struct node));
if(tmp == NULL)
printf("out of space");
else {
tmp->data = x;
tmp->next = s->next;
s->next = tmp;
}
}
void pop(stack s)
{
if(!is_empty(s)) {
ptr_to_node tmp = s->next;
s->next = s->next->next;
free(tmp);
} else
printf("Empty stack");
}
elem top(stack s)
{
// if(is_empty(s))
// printf("empty stack");
// else
// return s->next->data;
//
// return -1;
//
/* tune version */
if(!is_empty(s))
return s->next->data;
printf("empty stack");
return 0;
}
void print_stack(stack s)
{
printf("--------\n");
while(!is_empty(s)) {
printf(" %d\n", s->next->data);
s = s->next;
}
printf("--------\n");
}
void test()
{
stack s;
s = create_stack();
push(1, s);
push(2, s);
print_stack(s);
push(3, s);
push(4, s);
push(5, s);
print_stack(s);
printf("%d\n",top(s));
pop(s);
print_stack(s);
pop(s);
pop(s);
pop(s);
pop(s);
pop(s);
pop(s);
print_stack(s);
}
int main()
{
test();
return 0;
}
|