#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef short ElemType;
typedef short Status;
struct StackNode/* 链栈结点 */
{
ElemType data;
struct StackNode *next;
};
/* */
Status InitStack(struct StackNode* &s);
Status Push(struct StackNode* &s, ElemType e);
Status Pop(struct StackNode* &s, ElemType &e);
Status GetTop(struct StackNode* &s);
Status GetLength(struct StackNode* &s);
Status MenuPrint();
/* */
int main()
{
struct StackNode *S;/* 栈顶指针 */
short choice;
ElemType e;
InitStack(S);/* 初始化链栈 */
MenuPrint();
printf("Please input your choice: ");
while(1)
{
while(scanf("%hd", &choice) != 1)
{
while(getchar() != '\n') ;
printf("Now the input buffer has been cleaned, please input a number not a character.\n");
printf("Please input your choice: ");
}
if(choice == 5)
{
printf("Thanks for your using, see you.\n");
break;
}
switch(choice)
{
case 1:
printf("Please input the value of the element that will push: ");
scanf("%hd", &e);
Push(S, e);
break;
case 2:
if(Pop(S, e) == OK)
{
printf("The element that just have popped is %hd.\n", e);
}
else
{
printf("The stack is now empty, so there is no element that could pop.\n");
}
break;
case 3:
e = GetTop(S);
if(e == ERROR)
{
printf("The stack is now empty, so you can not get the top element.\n");
}
else
{
printf("Now the top element in the stack is %hd.\n", e);
}
break;
case 4:
e = GetLength(S);
printf("The number of the elements in the stack is now %hd.\n", e);
break;
case 5:
printf("Please input a valid choice from 1 to 5.\n");
break;
}
printf("Please input your choice: ");
}
}
/* 打印操作选项 */
Status MenuPrint()
{
printf("---------------------------链栈基本操作模拟系统---------------------------\n");
printf("---------------------------1. 入栈----------------------------------------\n");
printf("---------------------------2. 出栈----------------------------------------\n");
printf("---------------------------3. 取栈顶元素----------------------------------\n");
printf("---------------------------4. 获取栈内元素个数----------------------------\n");
printf("---------------------------5. 退出系统------------------------------------\n");
return OK;
}
/* 获取栈中元素个数 */
Status GetLength(struct StackNode* &s)
{
short len = 0;
struct StackNode *p = s;/* 一开始p指向栈顶 */
while(p != NULL)
{
len ++;
p = p -> next;
}
return len;
}
/* 取栈顶元素 */
Status GetTop(struct StackNode* &s)
{
if(s == NULL)
{
/* 栈空 */
return ERROR;
}
return s -> data;
}
/* 出栈 */
Status Pop(struct StackNode* &s, ElemType &e)
{
struct StackNode *p;
if(s == NULL)
{
/* 栈空 */
return ERROR;
}
e = s -> data;
p = s;
s = s -> next;
free(p);
return OK;
}
/* 入栈 */
Status Push(struct StackNode* &s, ElemType e)
{
struct StackNode *p = (struct StackNode*)malloc(sizeof(struct StackNode));
if(p != NULL)
{
p -> data = e;
p -> next = s;
s = p;/* 更新栈顶指针 */
return OK;
}
else
{
/* 动态内存申请失败 */
exit(0);
}
}
/* 初始化链栈 */
Status InitStack(struct StackNode* &s)
{
/* 链栈的初始化操作就是构造一个空栈, 因为没必要设头结点, 所以直接将栈顶指针置空即可 */
s = NULL;
return OK;
}