/*
供参考!
*/
# include
# include
# include
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,* PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK,* PSTACK;
void init(PSTACK pS);//栈初始化
void push(PSTACK pS,int val);//压栈
void traverse(PSTACK pS,int len);//遍历栈
int pop(PSTACK pS);//出栈
bool empty(PSTACK pS);//判断栈是否为空
int main(void)
{
STACK s;
printf("初始化栈:......\n");
init(&s);
printf("压栈.......\n");
printf("请输入要压入栈的元素个数:\t");
int len;
scanf("%d",&len);
int i,val;
for (i=0; i
printf("第%d个入栈元素:\t",(i+1));
scanf("%d",&val);
push(&s,val);
}
printf("遍历栈......\n");
traverse(&s,len);
return 0;
}
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;
}
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,int len)
{
int i,val;
for(i=0; i
val = pop(pS);
printf("%5d",val);
}
printf("\n");
return;
}
bool empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
{
return true;
}
else
return false;
}
int pop(PSTACK pS)
{
int val;
if (empty(pS))
{
return 1;
printf("栈为空!程序结束\n");
exit(-1);
}
else
{
PNODE r = pS->pTop;
val = r->data ;
pS->pTop = r->pNext;
free(r);
r = NULL;
return val;
}
}
/*
在vc++6.0中的输出结果是:
--------------------
初始化栈:......
压栈.......
请输入要压入栈的元素个数: 3
第1个入栈元素: 4
第2个入栈元素: 5
第3个入栈元素: 6
遍历栈......
6 5 4
-----------------------
*/