14栈
作者:互联网
栈(单口先进后出)
静态分配:用栈分配(入栈出栈)
动态分配:用堆分配(堆排序分配内存)
-
定义:
一种可以实现“先进后出”的储存结构,栈类似于箱子。
-
分类
静态栈
动态栈(链表)
-
算法
出栈
压栈
-
应用
函数调用
中断
表达式求值
内存分配
缓冲处理
迷宫(具体算法)
程序
# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
typedef struct Node
{
int data;
struct Node * pNext
}NOTE,* PNOTE;
typedef struct Stack
{
PNOTE pTop; //指向栈顶部
PNOTE pBottom;//指向栈底部(指向有效节点的下一个节点称头节点)
}STACK,* PSTACK;
void init(PSTACK);
void push(PSTACK, int);
void traverse(PSTACK);
bool empty(PSTACK pS);
bool pop(PSTACK, int *);//出栈一次,把出栈元素保存
void clear(PSTACK pS);//清空节点
int main(void)
{
STACK S;//STACK等价于struct Stack
init(&S);//初始化:产生空栈
push(&S, 1);//压栈:输入数据
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
push(&S, 6);
traverse(&S);//遍历输出
clear(&S);//清空
traverse(&S);//清空后遍历确认
if(pop(&S, &val))//保存出栈的值
{
printf("出栈成功,出栈元素是%d\n", val);
}
else
{
printf("出栈失败!\n");
}
return 0;
}
//初始化:pTop,pBottom都指向一个无用的头节点
void init(PSTACK pS)
{
pS->pTop = (PNOTE)malloc(sizeof(NOTE));//头节点地址放入
if(NULL==pS->pTop)
{
printf("动态分配内存失败!\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;//都指向头节点
pS->pTop->pNext = NULL;//或者:pS->Bottom->pNext = NULL;
}
}
//堆栈
void push(PSTACK pS, int val)
{
PNODE pNew = (PNOTE)malloc(sizeof(NOTE));
pNew = data = val;
pNew->pNext = pS->pTop;//新节点指针域指向头节点,pS->pTop不能换成pS->pBottom
pS->pTop = pNew;//pS->pTop指向新节点
return;
}
//遍历输出
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBattom)
{
printf("%d",p->data);
p = p->pNext;
}
printf("\n");
return;
}
//判断栈是否为空
bool empty(PSTACK pS)
{
if(pS->pTop==pS->pBattom)
return true;
else
return false;
}
//把sP所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的向量中,如果出栈成功返回ture,失败返回false
bool pop(PSTACK pS, int * pVal)
{
if(empt(pS))
{
return false;
}
else
{
PNOTE r = pS->pTop;//删除先定义变量保存要删除节点地址,之后释放掉
pS->pTop = r->pNext;//pS->pTop指针指向下一个
*pVal = r->data;//r->data赋值给Val
free(r);//释放内存
r = NULL;//清空节点内存
return true;
}
}
//clear:清空栈内数据
void clear(PSTACK pS)
{
if(empty(pS))
{
return;
}
else
{
PNOTE p = pS->pTop;
PNOTE q = NULL;
while(p!=pS->pBottom)
{
q = p->pNext;//q指向p的下一个元素,pTop = p->pNext;也可以
free(p);//释放p的内存
p = q;//从下个节点重新如此
}
pS->pTop = pS->pBottom;//pTop代替q,最后pS->pTop = pS->pBottom自动达到
}
}
标签:pS,出栈,14,void,PSTACK,pTop,节点 来源: https://www.cnblogs.com/chentongxue/p/16434182.html