首页 > 其他分享 >数据结构作业的代码——————栈的链式实现

数据结构作业的代码——————栈的链式实现

时间:2022-10-18 16:33:06浏览次数:80  
标签:current return cout 作业 栈顶 break StackNode 链式 数据结构


作业code2:

  • 仿照作业​​code1​​的功能,将课本上链表的实现栈的功能完整实现
  • 需要通过main函数调用并能进行友好的人机交互输入
#include<bits/stdc++.h>
#define
#define
#define
#define
#define

using namespace std;

typedef struct StackNode{//构造栈的节点
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;

LinkStack S,p;

Status InitStack(LinkStack &S)//初始化栈
{
S=NULL;
return OK;
}

Status Push(LinkStack &S,SElemType &e)//在栈顶插入元素e
{
p = new StackNode; //生成新节点
p->data = e; //将新节点数据域置为e
p->next = S; //将新节点插入栈顶
S = p; //修改栈顶指针为p;
return OK;
}

Status Pop(LinkStack &S,SElemType &e)//删除栈顶元素,用e返回其值
{
if(S == NULL) return ERROR; //栈空
e = S->data; //将栈顶元素赋给e
p = S; //用p临时保存栈顶元素空间,以备释放
S = S->next; //修改栈顶指针
delete p; //释放栈顶元素的空间
return OK; //
}

Status GetTop(LinkStack S)
{
if(S != NULL)
return S->data;
}

void display(struct StackNode* head)//遍历栈
{
struct StackNode *current;
current = head;
if(current!= NULL)
{
printf("Stack: ");
do
{
printf("%d ",current->data);
current = current->next;
}
while (current!= NULL);
printf("\n");
}
else
{
printf("The Stack is empty!\n");
}
}

int empty(struct node* head)
{
return head == NULL ? 1 : 0;
}

void menu()
{
cout<<" menu:"<<endl;
cout<<"1.进栈"<<endl;
cout<<"2.出栈"<<endl;
cout<<"3.输出"<<endl;
cout<<"4.menu"<<endl;
cout<<"0.结束"<<endl;
}

void preface()
{
printf(" *********************************************\n"
" * *\n"
" * 此程序的功能: *\n"
" * 将整数类型的数据进行栈的操作 *\n"
" * *\n"
" *********************************************\n"
"\n\n"
);
}

int main()
{
SElemType e,x;
InitStack(S);
preface();
menu();
int choose;
while(true)
{
cout<<"\n请选择:";
cin>>choose;
int k=0;
switch(choose)
{
case 1:
cout<<"请输入需要进栈的个数:";
cin>>x;
cout<<"请输入"<<x<<"个元素:";
while(x--)
{
cin>>e;
Push(S,e);
}
break;
case 2:
if(Pop(S,e))
cout<<"出栈的元素是"<<e<<endl;
else
printf("The Stack is empty!\n");
break;
case 3:
display(S);
break;
case 4:
menu();
break;
case 0:
k=1;
break;
default:
cout<<"请重新输入!";
break;
}
if(k) break;
}
return 0;
}

参考:


标签:current,return,cout,作业,栈顶,break,StackNode,链式,数据结构
From: https://blog.51cto.com/u_15834888/5767185

相关文章