#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct stacknode ///结构节点的定义
{
int data;
struct stacknode *next;
}StackNode,*LinkStack;
int StackEmpty(LinkStack top) ///栈判空
{
if(top->next==NULL)
return 1;
else
return 0;
}
void Push(LinkStack top,int value) ///入栈
{
StackNode * newp = (StackNode *)malloc(sizeof(StackNode));
if(newp != NULL)
{
newp->data=value;
newp->next=top->next;
top->next=newp;
}
else
cout<<"没有有效的内存空间存储新的节点"<<endl;
return ;
}
int Pop(LinkStack top) ///出栈
{
StackNode * temp;
int t;
if(StackEmpty(top))
cout<<"当前栈是空的!!!"<<endl;
else
{
temp=top->next;
t=temp->data;
top->next = temp->next;
free(temp);
}
return t;
}
void PrintStack(LinkStack top) ///打印操作
{
if(top->next==NULL)
cout<<"当前栈是空的!!!"<<endl;
else
{
while(top->next!=NULL)
{
cout<<top->next->data<<" ";
top=top->next;
}
}
}
int StackTop(LinkStack top) ///返回栈顶元素
{
if(StackEmpty(top))
cout<<"当前栈是空的!!!"<<endl;
return top->next->data;
}
int StackLen(LinkStack top) ///栈的长度
{
int len=0;
while(top->next!=NULL)
{
len++;
top=top->next;
}
return len;
}
void DestroyStack(LinkStack top) ///栈的销毁
{
LinkStack q;
q=top->next;
while(top!=NULL)
{ ///这个部分那个博客人写错了,害死我了,他居然把头节点给释放掉了 汗、
top=q->next;
free(q); ///销毁以后,原top的指向位置(他所存放的值还是之前那个,只不过此时是野指针)
q=top;
}
printf("销毁成功");
}
void InitStack(LinkStack top) ///初始化栈+清空操作
{
top->next=NULL;
}
void instruction(void) ///功能界面说明
{
cout<<"0------退出程序"<<endl
<<"1------入栈操作"<<endl
<<"2------出栈操作"<<endl
<<"3------取栈顶元素"<<endl
<<"4------判断栈是否为空"<<endl
<<"5------返回栈的元素个数"<<endl
<<"6------####初始化栈###"<<endl
<<"7------显示栈"<<endl
<<"8------销毁栈"<<endl
<<"9------退出程序"<<endl;
}
int main() ///主函数部分
{
LinkStack top=NULL;
top=(LinkStack)malloc(sizeof(StackNode)); ///头节点
instruction();
int i,value;
cin>>i;
while(i)
{
switch(i)
{
case 1:
InitStack(top);
cout<<"请输入一个整数,并终止到0结束!!!"<<endl;
cin>>value;
while(value!=0)
{
Push(top,value);
cin>>value;
}
PrintStack(top);
cout<<endl;
break;
case 2:
if(top->next!=NULL)
cout<<"栈顶元素是: "<<Pop(top)<<endl;
else
cout<<"当前栈是空的!!!"<<endl;
break;
case 3:
if(StackEmpty(top)==1)
cout<<"当前栈是空的!!!"<<endl;
else
cout<<StackTop(top)<<endl;
break;
case 4:
if(StackEmpty(top)==1)
cout<<"当前栈是空的!!!"<<endl;
else
cout<<"当前栈是空的!!!"<<endl;
break;
case 5:
if(StackEmpty(top)==1)
cout<<"当前栈是空的!!!"<<endl;
cout<<StackLen(top)<<endl;
cout<<endl;
break;
case 6: InitStack(top);break;
case 7:
PrintStack(top);
cout<<endl;
break;
case 8:
DestroyStack(top);
cout<<endl;
top->next=NULL; ///这一步很重要,否则会造成无元素还是输出任意数的结果
break;
case 9: goto end;break; ///有意思的goto语句
default:
cout<<"无效的选择!!!"<<endl;
break;
}
instruction();
cin>>i;
}
end:;
return 0;
}