#include <stdio.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);
bool pop(PSTACK, int *);
void clear(PSTACK);
int main(void)
{
STACK S; //内存中有了个栈pTop,pBottom
push(&S,122);
push(&S,233);
clear(&S);
traverse(&S);
push(&S,122);
push(&S,233);
traverse(&S);
int val;
if(pop(&S,&val))
{
printf("出栈成功,出栈元素%d\n",val);
}
else
{
printf("出栈失败!");
}
return 0;
}
void init(PSTACK pStack)
{
pStack->pTop = (PNODE)malloc(sizeof(NODE));
if(NULL == pStack->pTop)
{
printf("动态内存分配失败!\n");
exit(-1);
}
else {
pStack->pBottom = pStack->pTop;
pStack->pTop->pNext = NULL;
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
return;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
return;
}
bool empty(PSTACK pS)
{
if(pS->pTop == pS->pBottom)
{
return true;
}
else
{
return false;
}
}
bool pop(PSTACK pS, int * pVal)
{
if(empty(pS))
{
return false;
}
else
{
PNODE r = pS->pTop;
*pVal = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
}
void clear(PSTACK pS)
{
if(empty(pS))
{
return;
}
else
{
PNODE p = pS->pTop;
PNODE q = NULL;
while(p != pS->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
}