数据结构_链队列实验——火车车厢重排问题

//LinkQueue.h
#ifndef LinkQueue_H
#define LinkQueue_H
#define NULL 0
struct Node{
	int data;
	Node* next;
};

class LinkQueue{
public:
	LinkQueue();  //构造
	~LinkQueue();  //析构
	void Enqueue(int x);// 插入
	int DeQueue();  // 删除队首
	int GetQueue();  //取队首元素
	int GetRQueue();  //取队尾元素
	int Empty();  //判空操作
private:
	Node* front;  //队首指针
	Node* rear;  //队尾指针
};

#endif;


//LinkQueue.cpp
#include "LinkQueue.h"

LinkQueue::LinkQueue(){
	Node* s = NULL;
	s = new Node;
	s->next = NULL;
	front = rear = s;
}

LinkQueue::~LinkQueue(){
	Node* p = NULL;
	while(front!=NULL)
	{
		p = front->next;
		delete front;
		front = p;
	}
}

void LinkQueue::Enqueue(int x){
	Node* s = NULL;
	s = new Node;
	s->data = x;
	s->next = NULL;
	rear->next = s; rear = s;
}

int LinkQueue::DeQueue(){
	Node* p = NULL;
	int x;
	if(rear == front) throw "下溢";
	p = front->next;
	x = p->data;
	front->next = p->next;
	if(p->next == NULL) rear = front;
	delete p;
	return x; 
}

int LinkQueue::GetQueue(){
	if(front!=rear) return front->next->data;
	else return -(1<<30);  //错误标记
}
int LinkQueue::GetRQueue(){
	if(front!=rear) return rear->data;
	else return -(1<<30);  //错误标记
}
int LinkQueue::Empty(){
	if(front == rear) return 1;
	return 0;
}

//LinkQueue_main.cpp
#include
using namespace std;
#include "LinkQueue.h"

int main(){
	LinkQueue k[3]; //三个缓冲轨
	int num[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //九节火车车厢
	int nowOut = 1; //  要输出的车厢编号
	for(int i = 0; i< 9; i++){//依次取入轨中的每一个车厢的编号
		if(num[i] == nowOut) {
			cout << nowOut << "  ";
			nowOut++;
		}
		else {
			for(int j = 0; j < 3; j++){
				//考虑每一个缓冲轨
				int c = k[j].GetQueue();
				if(c == nowOut){
					k[j].DeQueue();
					cout << nowOut << "  ";
					nowOut++;
				}
			}
			//缓冲轨队列的队首元素也都不等于nowOut
			int MAXrear = -(1<<30);
			int bstflag = -1;
			for(int l = 0; l < 3; l++) {
				//比较k个队尾元素
				if(MAXrear

数据结构_链队列实验——火车车厢重排问题_第1张图片
 
 

你可能感兴趣的:(数据结构_链队列实验——火车车厢重排问题)