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

//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<iostream>
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<k[l].GetRQueue()&&k[l].GetRQueue()){
					MAXrear = k[l].GetRQueue();
					bstflag = l; 
				}
				if(num[i]<MAXrear) {
					cout << "无法重排 ,程序运行结束!"<< endl;
					return 0;
				}
				else k[l].Enqueue(num[i]);
				
			}
		}
	}
	cout << endl;
	return 0;
}


                
  • 3
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值