/*
栈的构造与操作
初始化
压栈
出栈
遍历
清空
*/
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
typedef struct Node
{
int data;
struct Node * pNext;
}* PNODE, NODE;
typedef struct STACK
{
PNODE pTop;
PNODE pBottom;
}* PSTACK, STACK;
//初始化
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if (!pS->pTop)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{
pS->pTop->pNext = NULL;
pS->pBottom = pS->pTop;
}
return;
}
//压栈
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (!pNew)
{
printf("内存分配失败!\n");
exit(-1);
}
else
{
pNew->pNext = pS->pTop;
pNew->data = val;
pS->pTop = pNew;
printf("压栈成功!\n");
}
return;
}
//遍历
void traverse(PSTACK pS)
{
PNODE pTemp = pS->pTop;
if (!pTemp->pNext)
{
printf("空栈,遍历失败!\n");
return;
}
else
{
while (pTemp->pNext)
{
printf("%d\n", pTemp->data);
pTemp = pTemp->pNext;
}
printf("遍历完毕!\n");
}
return;
}
//出栈
void pop(PSTACK pS)
{
int val;
if (!pS->pTop->pNext)
{
printf("空栈,出栈失败!\n");
}
else
{
val = pS->pTop->data;
pS->pTop = pS->pTop->pNext;
printf("出栈成功,出栈元素:%d\n", val);
}
return;
}
//清空
void clear(PSTACK pS)
{
PNODE pTemp;
if (!pS->pTop->pNext)
{
printf("栈空!\n");
return;
}
else
{
while (pS->pTop->pNext)
{
pTemp = pS->pTop;
pS->pTop = pS->pTop->pNext;
free(pTemp);
}
printf("清空成功!\n");
}
return;
}
int main(void)
{
STACK s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
push(&s, 4);
push(&s, 5);
push(&s, 6);
traverse(&s);
pop(&s);
traverse(&s);
clear(&s);
traverse(&s);
return 0;
}