p.height = 0; /* 栈高度初始化为零 */
p = InitStack (p); /* 栈初始化 */
printf("Do you want to push stack(Y/N)?");
scanf(" %c", &ch);
while (ch == 'Y' || ch == 'y')
{
p = Push(p); /* 入栈 */
DisplyStack(p); /* 遍历栈 */
printf("Do you want to push stack(Y/N)?");
scanf(" %c", &ch);
}
printf("Do you want to pop stack(Y/N)?");
scanf(" %c", &ch);
while (ch == 'Y' || ch == 'y')
{
p = Pop(p); /* 出栈 */
DisplyStack(p); /* 遍历栈 */
printf("Do you want to pop stack(Y/N)?");
scanf(" %c", &ch);
}
return 0;
}
/* Function: 初始化栈顶、栈底、栈高度*/
LinkStack InitStack (LinkStack pStack)
{
pStack.top = pStack.bottom = NULL;
pStack.height = 0;
return pStack;
}
/* Function: 判断栈是否为空 */
int StackEmpty (LinkStack pStack)
{
if (pStack.top == NULL && pStack.bottom == NULL)
{
return Empty;
}
else
{
return Avail;
}
}
/* Function: 入栈 */
LinkStack Push (LinkStack pStack)
{
int data;
StackNode *temp;
if ((temp = (StackNode *)malloc(sizeof(StackNode))) == NULL)
{
printf("内存空间不足\n");
return pStack;
}
if (StackEmpty(pStack) == Empty) /* 如果栈为空 */
{
pStack.top = pStack.bottom = temp; /* 栈顶、栈底指针都指向新建节点 */
temp->next = NULL; /* 节点指针域为空 */
printf("Please input data");
scanf("%d", &data);
pStack.top->data = data;
pStack.height++;
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: 遍历栈 自顶到底*/
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;