数据结构–栈
include<stdio.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(PSTACK);//建立一个空
void push(PSTACK,int);//压
void traverse(PSTACK);//遍历输出
bool empty(PSTACK pS);//判断栈是否为空
void clear(PSTACK);//清空
bool pop(PSTACK , int *);//出栈
int main(void)
{
int val;//存放出栈元素的值
STACK s;
init(&s);//建立一个空栈
push(&s,1);//压栈
push(&s,2);
push(&s,3);
push(&s,4);
push(&s,5);
traverse(&s);//遍历输出
if(pop(&s,&val))
{
printf("出栈成功,出栈的值为:%d.\n",val);
}
else
{
printf("出栈失败!\n");
}
traverse(&s);//遍历输出
clear(&s);//清空
traverse(&s);//遍历输出
return 0;
}
//出栈
bool pop(PSTACK pS, int * pVal)
{
if(empty(pS))
return false;
else
{
PNODE p = pS->pTop;
*pVal = p->data;
pS->pTop = p->pNext;
free(p);
p = NULL;
return true;
}
}
//清空
void clear(PSTACK pS)
{
if(empty(pS))
return;
else
{
PNODE p = pS->pTop ;
PNODE q = NULL;
while(NULL != p)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
return;
}
//遍历输出
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
if(pS->pBottom == pS->pTop)
printf("栈为空!\n");
else
{
printf("栈的值为: ");
while(pS->pBottom != p)
{
printf("%d,",p->data);
p = p->pNext ;
}
printf("\n");
}
return;
}
//判断栈是否为空
bool empty(PSTACK pS)
{
if(pS->pBottom == pS->pTop )
return true;
else
return false;
}
void push(PSTACK pS,int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL == pNew)
{
printf("内存分配失败,终止程序!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
return;
}
//建立一个空
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if(NULL == pS->pTop)
{
printf("内存分配失败,程序终止!\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
return;
}