您的位置:首页 > 其它

栈的基本操作

2015-10-26 00:00 357 查看
摘要: 栈的基本操作

栈的一些操作

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

typedef struct Node
{
int data;
struct Node * next;
}Node,*PNode;

typedef struct Stack
{
PNode top;
}Stack,*PStack;

//函数声明
void showlist();
void selection(PStack S);
void InitStack(PStack S);
void PushStack(PStack S);
void PopStack(PStack S);
void PrintStack(PStack S);
bool EmptyStack(PStack S);
void GetTopElem(PStack S);
void GetCount(PStack S);

int main()
{
Stack s;
InitStack(&s);
selection(&s);
system("pause");
return 0;
}

void showlist()
{
system("color 3e");
cout<<"**********************************"<<endl;;
cout<<"************1.入栈****************"<<endl;
cout<<"************2.出栈****************"<<endl;
cout<<"************3.打印栈元素**********"<<endl;
cout<<"************4.栈顶元素元素********"<<endl;
cout<<"************5.栈元素个数**********"<<endl;
cout<<"************6.退出****************"<<endl;
cout<<"**********************************"<<endl;
cout<<"**********************************"<<endl;
}

void selection(PStack s)
{
int opt;
showlist();

while(1)
{
cout<<"请选择你的操作:";
cin>>opt;
switch(opt)
{
case 1:
PushStack(s);
break;
case 2:
PopStack(s);
break;
case 3:
PrintStack(s);
break;
case 4:
GetTopElem(s);
break;
case 5:
GetCount(s);
break;
case 6:
exit(-1);
}

}
}

//初始化
void InitStack(PStack S)
{
S->top=(PNode)malloc(sizeof(Node));
if(!S->top)
cout<<"初始化失败!"<<endl;
else
{
S->top=NULL;
cout<<"初始化栈成功!"<<endl;
}

}

//入栈
void PushStack(PStack S)
{
int n;
int x;
cout<<"请输入要入栈的个数:";
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"请输入第"<<i<<"个元素的值:";
cin>>x;

PNode p;
p=(PNode)malloc(sizeof(Node));//申请节点

p->data=x;
p->next=S->top;
S->top=p;
}
}

//打印栈元素
void PrintStack(PStack S)
{
PNode p;
p=S->top;    //指向栈顶元素
cout<<"遍历栈元素的结果是:";
if(EmptyStack(S))
cout<<"栈空,没有元素要打印!!"<<endl;
else
{
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
}
cout<<endl;
}

//出栈
void PopStack(PStack S)
{
PNode p;
p=S->top;
if(EmptyStack(S))
{
cout<<"栈空!"<<endl;
}
else
{
cout<<"出栈的元素是:"<<p->data<<endl;
S->top=p->next;
free(p);
}
}

//判空栈
bool EmptyStack(PStack S)
{
if(S->top==NULL)
return true;
else
return false;
}

void GetTopElem(PStack S)
{
if(EmptyStack(S))
cout<<"栈为空,没有栈顶元素!"<<endl;
else
{
cout<<"栈顶元素是:"<<S->top->data<<endl;
}
}

void GetCount(PStack S)
{
PNode p;
p=S->top;    //指向栈顶元素
int count=0;
cout<<"遍历栈元素的结果是:";
if(EmptyStack(S))
cout<<0<<endl;
else
{
while(p!=NULL)
{
count++;
p=p->next;
}
}
cout<<count;
cout<<endl;
}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: