return pStack;
}
else /* 栈不为空 */
{
temp->next = pStack.top;/* 新建节点指向原来的栈顶 */
pStack.top = temp; /* 栈顶指针指向新建节点 */
printf("Please input data");
scanf("%d", &data);
pStack.top->data = data;
pStack.height++;
return pStack;
}
}
二、出栈
/* Function: 出栈 */
LinkStack Pop (LinkStack pStack)
{
StackNode *Second;
if (StackEmpty(pStack) == Empty) /* 判断栈是否为空 */
{
printf("栈为空,无法出栈\n");
return pStack;
}
if (pStack.top == pStack.bottom) /* 如果出栈的元素为最后一个元素 */
{
printf("出栈元素为%d\n", pStack.top->data);
free(pStack.top);
pStack.top = pStack.bottom = NULL; /* 栈顶、栈底都指针都置为空 */
pStack.height--;
return pStack;
}
printf("出栈元素为%d\n", pStack.top->data);
Second = pStack.top->next; /* 指向栈顶的前一个元素*/
free(pStack.top); /* 释放栈顶节点 */
pStack.top = Second;/* 将头指针移动到新的栈顶节点 */
pStack.height--;
return pStack;
}
出栈时需要判断三种情况,第一种情况:栈为空、第二种情况:栈中只有一个元素、第三种情况:栈中元素大于等于两个
三、判断栈是否为空
/* Function: 判断栈是否为空 */
int StackEmpty (LinkStack pStack)
{
if (pStack.top == NULL && pStack.bottom == NULL)
{
return Empty;
}
else
{
return Avail;
}
}
四、遍历栈
/* Function: 遍历栈 自顶到底*/
void DisplyStack (LinkStack pStack)
{
if (StackEmpty(pStack) == Empty)
{
printf("栈为空,无法遍历\n");
return ;
}
printf("栈中元素[");
while (pStack.top != NULL)
{
printf("%d->", pStack.top->data);
pStack.top = pStack.top->next;
}
printf("]\n");
}
五、清空栈
/* Function: 清空栈 */
LinkStack DeletStack (LinkStack pStack)
{
StackNode *del;
while (pStack.top != NULL)
{
del = pStack.top->next; /* 栈顶节点的前一个节点 */
free(pStack.top); /* 释放节点 */
pStack.top = del; /* 栈顶指针移动到新栈顶 */
}
return pStack;
}
六、初始化栈顶、栈底指针和栈高度
/* Function: 初始化栈顶、栈底、栈高度*/
LinkStack InitStack (LinkStack pStack)
{
pStack.top = pStack.bottom = NULL;
pStack.height = 0;
return pStack;
}
链式栈实现完整代码
#include <stdio.h>
#include <stdlib.h>
#define Empty 0 /* 栈空 */
#define Avail 1 /* 栈可用 */
typedef struct SNode
{
int data;
struct SNode *next;
}StackNode;
typedef struct LStack
{
StackNode *top; /* 栈顶指针 */
StackNode *bottom; /* 栈底指针 */
int height; /* 链式栈高度 */
}LinkStack;
LinkStack InitStack (LinkStack pStack); /* 栈顶指针、栈底指针、栈高度初始化*/
LinkStack Push (LinkStack pStack); /* 入栈 */
LinkStack Pop (LinkStack pStack); /* 出栈 */
int StackEmpty (LinkStack pStack); /* 判断栈是否为空 */
LinkStack DeletStack (LinkStack pStack);/* 清空栈 */
void DisplyStack (LinkStack pStack); /* 遍历栈----自顶至底*/
int main()
{
LinkStack p;
char ch;