栈结构实现

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

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>


typedef struct Stack //定义栈模型
{
PNODE TOP;
PNODE BUTTOM;
}*PSTACK,STACK;

/*
栈定义的模型
初始化方法,压入栈的方法,出栈的方法,遍历的方法,
*/
//初始化栈的操作
void init_stack(PSTACK);
//压入栈
void push_stack(PSTACK, int);
//出栈
void pop_stack(PSTACK, int*);
//遍历
void traverse(PSTACK);
//是否为空
bool empty(PSTACK);
//clear;
void clear(PSTACK);
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
/*
实现上述栈的函数
*/
//初始化
void init_stack(PSTACK phead){
PNODE stack = (PNODE)malloc(sizeof(NODE));
if (stack == NULL){
printf("创建失败!");
return ;
}
phead->BUTTOM = stack;
phead->TOP = phead->BUTTOM;
phead->TOP->next = NULL;

}
//入栈
void push_stack(PSTACK phead, int val){
PNODE pnew = (PNODE)malloc(sizeof(NODE));
pnew->data = val;
pnew->next = phead->TOP;
phead->TOP = pnew;
}
//出栈
void pop_stack(PSTACK phead, int *val){
if (empty(phead))
{
return;
}
PNODE p = phead->TOP;
*val = p->data;
phead->TOP = p->next;
free(p);
p = NULL;
}
//遍历
void traverse(PSTACK phead){
PNODE p = phead->TOP;
while (phead->BUTTOM!=p)
{
printf("%d", p->data);
p = p->next;
}
}
//是否为空
bool empty(PSTACK phead){
if (phead->BUTTOM == phead->TOP)
return true;
return false;
}
//clear
void clear(PSTACK phead){
if (empty(phead))
return;
PNODE p = phead->TOP;
while (p != phead->BUTTOM)
{
phead->TOP = p->next;
free(p);
p = phead->TOP;
}
}

void main(){
STACK stack;
int val;
init_stack(&stack); //初始化
if (empty(&stack)) //
printf("空stack\n");
push_stack(&stack, 1);//push
push_stack(&stack, 2);
push_stack(&stack, 3);
traverse(&stack); //遍历
pop_stack(&stack, &val);
clear(&stack); //clear
pop_stack(&stack, &val);
printf("%d", val);
pop_stack(&stack, &val);
pop_stack(&stack,&val); //pop
system("pause");
}

版权声明:本文为博主原创,如若转载请标明出处https://dword.top/栈结构.html

-------------end-------------
0%