>n;coutcout0&&kcin>>k;coutif(k100)throw"输入错误";int*array=newint[n];coutfor(inti=0;icin>>array[i];coutfor(inti=0;icoutcoutLinkQueue*buffer" />
搜档网
当前位置:搜档网 › c++数据结构用队列实现火车车厢重排问题,分头文件的完整面向对象代码

c++数据结构用队列实现火车车厢重排问题,分头文件的完整面向对象代码

#include
#include"Permute.h"
using namespace std;
int main(){
try{
int n,k;
cout<<"请输入火车车厢数n:[n<100]\t";
cin>>n;cout<cout<<"请输入缓冲轨数k:[k>0&&kcin>>k;cout<
if(k<=0&&n<=0&&n>100)
throw"输入错误";


int *array=new int[n];
cout<<"请输入火车车厢入轨顺序"<for(int i=0;icin>>array[i];

cout<<"火车车厢入轨顺序为"<for(int i=0;icout<cout<LinkQueue *buffer;
buffer=new LinkQueue[k]; //动态建立k个缓冲轨队列
TrainPermute(array,buffer,n,k);

delete []array;
array=nullptr;
}
catch(char *s){
cout<}

return 0;
}
////////////////////////
#ifndef PERMUTE_H
#define PERMUTE_H
#include
using namespace std;
const int QueueSize = 100;
template
struct Node{
T data;
Node *next;
};
template
class LinkQueue{
private:
Node *front,*rear;
public:
LinkQueue();
virtual ~LinkQueue();
virtual void Trans(); //遍历缓冲轨
void EnQueue(T x);
T DeQueue();
T GetFront(){
if(front!=rear)
return front->next->data;
}
T GetRear(){
if(front!=rear)
return rear->data;
}
bool Empty(){
front==NULL?return 1:return 0;
}
friend void TrainPermute(int arr[],LinkQueue a[],int n,int k);
};
template
LinkQueue::LinkQueue(){
Node *s=new Node;
s->next=NULL;
front=rear=s;
}
template
LinkQueue::~LinkQueue(){
Node *p=front;
while(p!=NULL){
Node *q=p;
p=p->next;
delete q;
}
}
template
void LinkQueue::EnQueue(T x){
Node *s=new Node;
s->next=NULL;
s->data=x;
rear->next=s;
rear=s;
}
template
T LinkQueue::DeQueue(){
if(rear==front)
throw"下溢";
Node *p=front->next;
int x=p->data;
front->next=p->next;
if(p->next==NULL)
rear=front;
delete p;
return x;
}
template
void LinkQueue::Trans(){
Node *p=front->next;
while(p){
cout<data<<' ';
p=p->next;
}
}

void TrainPermute(int arr[],LinkQueue a[],int n,int k){
int i=0;
bool flag=1;//标记
while(iflag=0;
for(int m=0;mif(a[m].GetRear()a[m].EnQueue(arr[i]);
i++;flag=1;break;
}
if(a[m].front->next==NULL){
a[m].EnQueue(arr[i]);
flag=1;i++;break;
}
}
}
if(flag==0){
cout<<"车厢无法重排,算法结束"<}
else
{
for(int m=0;mcout<<"第"<<(m+1)<<"个缓冲轨的列车编号\t";
a[m].Trans();
cout<}
cout<for(int newout=1;newout<=n;newout++){//从1开始按升序出轨
for(int j=0;jif(a[j].GetFront()==newout)
{cout<}
}

}
}
#endif

相关主题