-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.c
More file actions
151 lines (132 loc) · 2.21 KB
/
Copy pathstack.c
File metadata and controls
151 lines (132 loc) · 2.21 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stack.h"
/**
* Create an empty stack
* @return
*/
Stack create_stack()
{
Stack s = (Stack) malloc(sizeof(Node));
if(s == NULL) {
printf("内存分配失败,程序退出!\n");
exit(-1);
}
s->next = NULL;
return s;
}
/**
* Traverse stack
* @param s
*/
void traverse_stack(Stack s) {
if (is_empty(s) == true) {
printf("栈为空\n");
}
printf("当前栈内元素: ");
while (s->next != NULL) {
if (s->next->next == NULL) {
printf("%d", s->next->data);
}else {
printf("%d-->", s->next->data);
}
s = s->next;
}
}
/**
* Push element into stack
* @param s
* @return
*/
bool push(Stack s, DataType data)
{
Stack new_node = (Stack) malloc(sizeof(Node));
if(new_node == NULL) {
printf("内存分配失败,程序退出!\n");
return false;
}
new_node->data = data;
new_node->next = s->next;
s->next = new_node;
return true;
}
/**
* Pop element of stack
* @param s
* @return
*/
DataType pop(Stack s)
{
if (is_empty(s) == true) {
printf("栈为空!\n");
return -1;
}
DataType data = get_top_element(s);
Stack pop_node = s->next;
s->next = s->next->next;
free(pop_node);
return data;
}
/**
* Get the top element of stack
* @param s
* @return
*/
DataType get_top_element(Stack s)
{
if (is_empty(s) == true) {
printf("栈为空!\n");
}
return s->next->data;
}
/**
* Get size of stack
* @param s
* @return
*/
int get_stack_size(Stack s)
{
int size = 0;
while(s->next) {
size++;
}
return size;
}
/**
*
* @param s
* @return
*/
bool is_empty(Stack s)
{
if (s->next == NULL) {
return true;
} else {
return false;
}
}
/**
* Make stack empty
* @param s
*/
void empty_stack(Stack s)
{
if (is_empty(s) == true) {
printf("栈为空!\n");
}
while (s->next != NULL) {
Stack node = s->next;
s->next = s->next->next;
free(node);
}
printf("清空栈成功\n");
}
/**
*
* @param s
*/
void delete_stack(Stack s)
{
free(s);
}