分类:
静态栈
动态栈
算法:
出栈
入栈
应用:
函数调用
中断
表达式求值
内存分配
缓冲处理
迷宫
</pre><pre name="code" class="cpp"><span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">#include <stdio.h></span>
#include <conio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE , * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom; //指向头结点,最后一个有效元素的下面的节点
}STACK, * PSTACK;
void init_Stack(PSTACK);
bool empty(PSTACK pS);
void push(PSTACK, int val);
bool pop(PSTACK,int * );
void traverse(PSTACK );
void clear(PSTACK);
int main(void)
{
STACK S; //STACK等价于struct Stack,内存里就有两个成员pTop,pBottom
int val;
init_Stack(&S);
push(&S, 1);
push(&S, 2);
push(&S, 3);
push(&S, 4);
push(&S, 5);
push(&S, 6);
traverse(&S);
if (pop(&S, &val))
{
printf_s("出栈成功,出栈的元素是%d\n", val);
}
else
printf_s("出栈失败!\n");
clear(&S);
traverse(&S);
system("PAUSE");
return 0;
}
void init_Stack(PSTACK pS)
{
pS->pBottom = (PNODE)malloc(sizeof(NODE));
if (NULL == pS->pBottom)
{
printf_s("状态内存分配失败!\n");
exit(-1);
}
else
{
pS->pTop = pS->pBottom;
pS->pTop->data = NULL;
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf_s("状态内存分配失败!\n");
exit(-1);
}
else
{
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
}
return;
}
void traverse(PSTACK pS)
{
PNODE q = pS->pTop;
if (empty(pS))
{
printf_s("栈为空");
}
while( q != pS->pBottom)
{
printf_s("%d ", q->data);
q = q->pNext;
}
printf_s("\n");
return;
}
bool empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
return true;
else
return false;
}
//把pS所指向的栈出栈一次,并吧出栈的原色存入pVal形参所指向的变量中,如果出栈失败则返回false
bool pop(PSTACK pS,int * pVal)
{
PNODE q;
if (empty(pS))
{
return false;
}
else
{
* pVal = pS->pTop->data;
q = pS->pTop;
pS->pTop = q->pNext;
free(q);
q = NULL;
return true;
}
}
void clear(PSTACK pS)
{
PNODE p = pS->pTop;
while (p != pS->pBottom)
{
pS->pTop = pS->pTop->pNext;
free(p);
p = NULL;
p = pS->pTop;
}
return;
}