1.实验目的:
(1)掌握顺序栈的和链队列的实现;
(2)能利用栈和队列的基本运算解决实际问题;
2.实验要求:
车场是一个可停放n辆汽车的狭长通道,且只有一个大门可供进出(栈结构)。
汽车在停车场内按车辆到达的先后顺序依次排列。
若停车场内的已停满汽车,则后来的车只能在门外的变道上等候,一旦停车场内有车开走,
则排在便道上的第一辆车即可进入(队列结构)。
每辆停放在停车场的车,在离开时按其在停车场停留时间长短交费(在这里假设车不能从门外等侯便道上直接开走)。
试设计一个实现停车场管理的程序,按照从终端输入数据序列进行模拟管理 。
(1) 采用顺序栈和链式队列实现;
(2) 每一组输入数据包括三个数据项:汽车牌照,到达或离去的标记和时刻。;
(3) 对每一组输入数据进行操作后的输出信息为:车辆到达:输出车辆在停车场或便道上的停车位置;车辆离去:输出停留时间和费用(在便道上等候不收费)
3.实验代码:
(懒得改手写栈和队列了,stl真快乐)
#include<bits/stdc++.h> using namespace std; const int maxn=110; struct node { string id;///车牌号 int flag;///表示是到达还是离开:到达是1,离开是0 int time;///表示到达或离开的时间 }; map<string,bool>mp;///停车场是否有该车 int n,cost; stack<node>stk; queue<node>q; void showmain() { cout<<"**********菜单*************"<<endl; cout<<"1.修改停车场的容量"<<endl; cout<<"2.输入车辆信息"<<endl; cout<<"3.修改停车一小时的费用"<<endl; cout<<"4.查看停车场的车辆情况"<<endl; cout<<"5.查看变道的车辆情况"<<endl; cout<<"6.退出系统"<<endl; } void change_n() { int tmp; cin>>tmp; if(tmp>n) { while(stk.size()<=n) { node t=q.front(); t.time=t.time; q.pop(); stk.push(t); mp[t.id]=1; } } else { while(stk.size()>n) { node t=stk.top(); stk.pop(); mp[t.id]=0; q.push(t); } } n=tmp; } void change_cost() { cin>>cost; } void add_car() { cout<<"请输入车辆的相关信息:"<<endl; node t; cin>>t.id>>t.flag>>t.time; if(t.flag) //到达 { if(stk.size()==n) { q.push(t);///停车场满了,只在路上停留 cout<<"车牌号为"<<t.id<<"的车在路上的"<<q.size()<<"号位置"<<endl; } else { stk.push(t);///直接将车停到停车场里 cout<<"车牌号为"<<t.id<<"的车在停车场的"<<stk.size()<<"号位置"<<endl; mp[t.id]=1; } } else ///离开 { if(!mp[t.id]) { puts("停车场没有该车"); return ; } mp[t.id]=0; node tt=stk.top(); stk.pop(); while(stk.size()<n&&!q.empty()) { node tmp=q.front(); tmp.time=t.time; q.pop(); stk.push(tmp); mp[tmp.id]=1; } cout<<"车牌号为"<<t.id<<"的车的花费为"<<(t.time-tt.time)*cost<<endl; } cout<<stk.size()<<"*************"<<q.size()<<endl; } void show_park() { ///先进后出 vector<node>v; int cnt=stk.size(); while(!stk.empty()){ v.push_back(stk.top()); cout<<"车牌号为"<<stk.top().id<<"的车在停车场的"<<cnt--<<"号位置"<<endl; stk.pop(); } reverse(v.begin(),v.end()); for(int i=0;i<v.size();i++){ stk.push(v[i]); } } void show_road() { vector<node>v; int cnt=1; while(!q.empty()){ v.push_back(q.front()); cout<<"车牌号为"<<q.front().id<<"的车在路上的"<<cnt++<<"号位置"<<endl; q.pop(); } for(int i=0;i<v.size();i++){ q.push(v[i]); } } int main() { puts("请输入停车场的容量:"); cin>>n; puts("请输入停车一小时的费用:"); cin>>cost; while(1) { showmain(); cout<<"请输入您想进行的操作:"<<endl; int op; cin>>op; if(op==1) change_n(); else if(op==2) add_car(); else if(op==3) change_cost(); else if(op==4) show_park(); else if(op==5) show_road(); else if(op==6) return 0; } return 0; }