动态栈
typedef int ElemType;
struct Node
{
int data;
struct Node * pNext;
};
struct Stack
{
struct Node * pTop;
struct Node * pBase;
};
void init_stack(struct Stack * pS)
{
pS->pBase = (struct Node *) malloc(sizeof (struct Node));
if (!pS->pBase)
exit(-1);
pS->pTop = pS->pBase ;
pS->pBase->pNext = NULL;
}
bool is_empty(struct Stack * pS)
{
if (pS->pBase == pS->pTop)
return true;
else
return false;
}
void clear(struct Stack * pS)
{
if (is_empty(pS))
return;
struct Node * p, *q;
p = pS->pTop;
while (p != pS->pBase)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBase;
}
void push(struct Stack * pS, ElemType val)
{
struct Node * pNew;
pNew = (struct Node *) malloc(sizeof (struct Node));
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
}
bool pop(struct Stack * pS, ElemType * val)
{
if (is_empty(pS))
return false;
struct Node * r;
r = pS->pTop;
*val = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
void traverse(struct Stack * pS)
{
struct Node * p = pS->pTop;
while (p != pS->pBase)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
}
测试
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
int main()
{
struct Stack S;
init_stack(&S);
push(&S, 2);
push(&S, 3);
push(&S, 7);
push(&S, 11);
traverse(&S);
ElemType val;
pop(&S, &val);
printf("val = %d\n", val);
traverse(&S);
return 0;
}