数据结构编程练习(四)
1 编写顺序栈类,实现其相应功能。
2 利用所编写的栈类,实现下列应用之一或多个。
(1)十进制数转换为八进制数。
(2)利用栈实现12+5*(2+3)*6/2-4 的求解
(3)利用栈解决迷宫问题:
一个迷宫的实例,如右图所示:
图中紫色方块为障碍,不能通行;
白色方块可以通行;
行进方向4个或8个;
需求出从入口到出口的一条通道。
代码实现(迷宫实现时有点问题):
#include "iostream"
#include "cstdio"
using namespace std;
#define max 100
#define a 5
#define b 5
int M[a][b];//迷宫
struct maze
{
int x;//x坐标
int y;//y坐标
};
maze start,end,next;
bool flag=0;
class stack
{
public:
stack();
~stack();
bool empty();
bool full();
int push(int x);
int pop();
int get_top(int &x);
int change(int x);
int findMaze(maze cur);
int print();
private:
int data[max];
int top;
};
//顺序栈的初始化
stack::stack()
{
top=-1;
}
stack::~stack()
{
}
//判空
bool stack::empty()
{
if(top==-1)
return true;
else
return false;
}
//判满
bool stack::full()
{
if(top==max-1)
return true;
else
return false;
}
//入栈
int stack::push(int x)
{
if(full())
{
cout<<"栈已满"<<endl;
return 0;
}
else
{
top++;
data[top]=x;
return 1;
}
}
//出栈
int stack::pop()
{
if(empty())
{
cout<<"栈为空,不能出栈"<<endl;
return 0;
}
else
{
// cout<<data[0]<<"已出栈"<<endl;
data[top]=-1;
top--;
return 1;
}
}
//取栈顶元素
int stack::get_top(int &x)
{
if(empty())
{
cout<<"栈为空,无栈顶元素"<<endl;
return 0;
}
else
{
x=data[top];
return 1;
}
}
//将十进制转化为八进制
int stack::change(int x)
{
int i;
while(x%8)
{
i=x%8;
x=x/8;
push(i);
}
cout<<"转化为的八进制数为:";
while(!empty())
{
get_top(i);
cout<<i;
pop();
}
cout<<endl;
return 1;
}
int stack::print()
{
cout<<endl;
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
{
cout<<M[i][j]<<" ";
if(j==b-1)
cout<<endl;
}
return 0;
}
//迷宫问题
int stack::findMaze(maze cur)
{
maze dir[4]={{0,1},{-1,0},{1,0},{0,-1}};
for(int i=0;i<4;i++)
{
next.x=cur.x+dir[i].x;
next.y=cur.y+dir[i].y;
if(M[next.x][next.y]==1)
{
push(next.y);
push(next.x);
M[next.x][next.y]=2;
if(next.x==end.x&&next.y==end.y)
{
flag=1;
int n;
print();
cout<<"长度为:"<<top/2<<endl;
while(!empty())
{
get_top(n);
cout<<n<<" ";
pop();
get_top(n);
cout<<n<<endl;
pop();
}
return 1;
}
else
findMaze(next);
if(top!=-1)
{
pop();
pop();
}
}
}
}
int main()
{
// freopen("flyerin.txt","r",stdin);
stack obj1;
int n;
cout<<"请输入顺序栈,以-1作为结束标志:";
while(cin>>n&&n>=0)
obj1.push(n);
obj1.empty();
obj1.full();
obj1.get_top(n);
cout<<"栈顶元素为:"<<n<<endl;
while(!obj1.empty())
obj1.pop();
cout<<"请输入一个十进制数:";
cin>>n;
obj1.change(n);
cout<<"请输入迷宫:";
for(int i=0;i<a;i++)
for(int j=0;j<b;j++)
cin>>M[i][j];
cout<<"请输入迷宫的入口和出口:";
cin>>start.x>>start.y>>end.x>>end.y;
obj1.push(start.x);
obj1.push(start.y);
M[start.x][start.y]=2;
obj1.findMaze(start);
if(!flag)
cout<<"没有可行路径"<<endl;
return 0;
}