#include<iostream>
using namespace std;
#include <stdlib.h>
#define MAXSIZE 100
#define ok 1
#define error -1;
#define overflow 0;
typedef int Status;
typedef int ElemType;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
Status InitStack(LinkStack &S);
Status Pop(LinkStack &S);
Status GetTop(LinkStack S);
Status Push(LinkStack &S, ElemType e);
Status out(LinkStack S);
Status StackEmpty(LinkStack S);
void menu()
{
cout<<"---------------------线性表的顺序表示和实现-------------------"<<endl;
cout<<" 1.初始化栈 2.元素入栈 3.删除栈顶元素 4.取栈顶元素"<<endl;
cout<<" 5.遍历栈 6.判断栈是否为空 0.结束 "<<endl;
cout<<"--------------------------------------------------------------"<<endl;
}
int main()
{
LinkStack S;
int choice;
while(1)
{
system("cls");
menu();
cout<<"Enter your choice:";
cin>>choice;
switch(choice)
{
case 1:
if(InitStack(S)==1)
cout<<"初始化成功";
system("pause");
break;
case 2:
int n;
ElemType e;
cout<<"请输入要输入元素的个数:";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>e;
Push(S,e);
}
system("pause");
break;
case 3:
Pop(S);
out(S);
system("pause");
break;
case 4:
cout<<"栈顶元素为";
cout<<GetTop(S);
system("pause");
break;
case 5:
out(S);
system("pause");
break;
case 6:
if(StackEmpty(S)==-1)
cout<<"不是空栈";
else
cout<<"是空栈";
system("pause");
break;
case 0:
exit(0);
break;
}
}
}
Status InitStack(LinkStack &S)
{
S=NULL;
return ok;
}
Status Pop(LinkStack &S)
{
ElemType e=0;
StackNode *p;
if(S==NULL)
return error;
e=S->data;
p=S;
S=S->next;
delete p;
return ok;
}
Status GetTop(LinkStack S)
{
if(S!=NULL)
return S->data;
}
Status Push(LinkStack &S, ElemType e)
{
StackNode *p;
p=new StackNode;
p->data=e;
p->next=S;
S=p;
return ok;
}
Status out(LinkStack S)
{
StackNode *p=S;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
Status StackEmpty(LinkStack S)
{
if(S->next==NULL)
return ok;
else
return error;
}
首先是一个自定义的阐述,函数声明,主函数(函数调用),函数的功能.
函数功能有输入采取主函数定义一个n,然后用传参的方式再采用一个for循环的方式来完成
输出是当栈顶指针等于栈底指针时就停止以此来作为while循环的条件
删除,输出栈顶指针
这个实验最应该关注的是记得要采用指针来做
不会的同学可以来看一下
当然也欢迎各位同学一起来讨论学习,一起进步
也欢迎各路大神指出不足,改进