目的要求
1.掌握栈、队列的思想及其存储实现。
2.掌握栈、队列的常见算法的程序实现。
实验内容
1.采用链式存储实现栈的初始化、入栈、出栈操作。
2.采用顺序存储实现栈的初始化、入栈、出栈操作。
3.采用链式存储实现队列的初始化、入队、出队操作。
4.采用顺序存储实现循环队列的初始化、入队、出队操作。
5.在主函数中设计一个简单的菜单,分别测试上述算法。
6. 利用栈实现数制转换(将一个十进制数转换成d进制数)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
#include<iomanip>
using namespace std;
typedef long long ll;
#define MAX 100
using namespace std;
struct lstack///栈的链式存储
{
int data;
lstack *next;
void InitStack()
{
next=NULL;
}
int Pop()
{
int e;
lstack *p;
p=next;
e=next->data;
next=next->next;
free(p);
return e;
}
void Push(int e)
{
lstack *p;
p=(lstack*)malloc(sizeof(lstack));
p->data=e;
p->next=next;
next=p;
}
bool empty()
{
if(next==NULL)
return 1;
return 0;
}
};
struct sxstack///栈的顺序存储
{
int top;
int stack[MAX];
void Initsxstack()
{
top=-1;
}
void Push(int a)
{
stack[++top]=a;
}
int Pop()
{
return stack[top--];
}
};
struct node///队列链式存储
{
int data;
node *next;
};
struct lqueue
{
node *front;
node *rear;
void InitQueue()
{
rear=(node*)malloc(sizeof(node));
rear->next=NULL;
front=(node*)malloc(sizeof(node));
front->next=rear;
}
void Push(int e)
{
node *p;
p=(node*)malloc(sizeof(node));
p->next=NULL;
rear->data=e;
rear->next=p;
rear=p;
}
int Pop()
{
node *p;
p=front;
front=front->next;
free(p);
return front->data;
}
bool empty()
{
if(front->next==rear)
return 1;
return 0;
}
};
struct sxqueue///队列顺序存储
{
int queue[MAX];
int front,rear;
void Initsxququ()
{
front=rear=0;
}
void Push(int a)
{
queue[rear++]=a;
}
int Pop()
{
return queue[front++];
}
};
void shuzhizhuanhuan(int x,int d)///数制转换
{
if(d<=1)
{
cout<<"输入有误,请重新输入!"<<endl;
return;
}
lstack a;
a.InitStack();
int ss=x;
while(x!=0)
{
int t=x%d;
x/=d;
a.Push(t);
}
cout<<ss<<"转化为"<<d<<"进制表示为:";
while(!a.empty())
cout<<a.Pop();
cout<<endl;
}
int main()
{
cout<<"创建链式存储与顺序存储栈,请输入元素的个数:"<<endl;
lstack a1;
sxstack a2;
a1.InitStack();
a2.Initsxstack();
int n;
cin>>n;
cout<<"请输入"<<n<<"个数"<<endl;
for(int i=0; i<n; i++)
{
int t;
cin>>t;
a1.Push(t);
a2.Push(t);
}
cout<<"链式存储栈的所有元素为:";
while(!a1.empty())
cout<<a1.Pop()<<' ';
cout<<endl<<endl;
cout<<"顺序存储栈的所有元素为:";
while(a2.top!=-1)
cout<<a2.Pop()<<' ';
cout<<endl<<endl;
cout<<"创建链式存储与顺序存储队列,请输入元素的个数:"<<endl;
lqueue a3;
sxqueue a4;
a3.InitQueue();
a4.Initsxququ();
int nn;
cin>>nn;
cout<<"请输入"<<nn<<"个数"<<endl;
for(int i=0; i<nn; i++)
{
int t;
cin>>t;
a3.Push(t);
a4.Push(t);
}
cout<<"链式存储队列的所有元素为:";
while(!a3.empty())
cout<<a3.Pop()<<' ';
cout<<endl;
cout<<"顺序存储队列的所有元素为:";
while(a4.front<a4.rear)
cout<<a4.Pop()<<' ';
cout<<endl;
int x,d;
cout<<"现在能进行数制转换,请先输入你想转换的数,再输入想转换的数制:"<<endl;
while(cin>>x>>d)
shuzhizhuanhuan(x,d);
return 0;
}