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
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>

typedef struct Node{
int data;
struct Node* next;
}Node;

typedef struct Stack
{
Node* top;
Node* bottom;
}Stack;

//初始化
void init (Stack* pstack)
{
pstack->bottom = malloc(sizeof(Node));
pstack->bottom->next = NULL;
pstack->top = pstack->bottom;
pstack->top->next = NULL;
}
//遍历
void traverse(Stack pstack)
{
if(pstack.bottom == pstack.top)
{
printf("stack empty\n");
return;
}
Node *p = pstack.top;
while(p->next != NULL)
{
printf("%d,", p->data);
p = p->next;
}
printf("\n");
}
//入栈
void push(Stack* pstack, int val)
{
Node* pnew = malloc(sizeof(Node));
pnew->data = val;
pnew->next = pstack->top;
pstack->top = pnew;
}
void pop(Stack* pstack, int *val)
{
if(pstack->bottom == pstack->top)
{
printf("pop error\n");
return ;
}
*val = pstack->top->data;
Node* ptop = pstack->top;
pstack->top = pstack->top->next;
free(ptop);
ptop = NULL;
}
//清空
void clear(Stack* pstack)
{
while(pstack->top != pstack->bottom)
{
int val;
pop(pstack,&val);
}
}
int main()
{
Stack stack;
init(&stack);
push(&stack,6);
push(&stack,7);
push(&stack,8);
traverse(stack);
int val;
pop(&stack,&val);
printf("num:%d\n",val);
traverse(stack);
clear(&stack);
traverse(stack);
push(&stack,7);
traverse(stack);
return 0;
}