-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack.c
95 lines (85 loc) · 1.64 KB
/
stack.c
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
/*
* @Description:
* @LastEditors: hsjfans
* @Email: [email protected]
* @Date: 2019-04-11 14:42:27
* @LastEditTime: 2019-04-12 10:36:43
*/
#include "include/stack.h"
#include <stdlib.h>
#include <string.h>
StackNode *stack_node_new(Element e, StackNode *next)
{
StackNode *node = (StackNode *)malloc(sizeof(StackNode));
node->e = e;
node->next = next;
return node;
}
void free_node(StackNode *node)
{
if (node)
{
node->e = NULL;
node->next = NULL;
free(node);
}
}
Stack *stack_new()
{
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->length = 0;
return stack;
}
// delete the top of stack,meanwhile return it;
Element pop(Stack *stack)
{
if (is_empty(stack))
{
return NULL;
}
StackNode *node = stack->head;
stack->head = node->next;
stack->length--;
Element e = node->e;
free_node(node);
return e;
}
// get the top element of stack;
Element top(Stack *stack)
{
if (is_empty(stack))
{
return NULL;
}
return stack->head->e;
}
// push element to stack;
void push(Element e, Stack *stack)
{
StackNode *node = stack_node_new(e, stack->head);
stack->head = node;
stack->length++;
}
// check the stack is empty or not;
boolean is_empty(Stack *stack)
{
return stack->length == 0 ? 1 : 0;
}
// clear the stack as an empty;
void clear(Stack *stack)
{
StackNode *root = stack->head;
while (root)
{
StackNode *tmp = root->next;
free_node(root);
root = tmp;
}
stack->length = 0;
}
// destory the stack
void destory(Stack *stack)
{
clear(stack);
free(stack);
}