设有n个人站成一排,从左向右的便后分别为1~n,现在从左往右报数“1,2,1,2,…”,数到“1”的人出列,数到“2”的立即站到队伍的最右端。报数过程反复进行,直到n个人都出列为止。要求给出他们的出列顺序。(用队列解决)
例如,当n=8时初始序列为:1 2 3 4 5 6 7 8
则出列顺序为:1 3 5 7 2 6 4 8
#include <iostream>
using namespace std;
struct Node//队列中的结点定义
{
int data;
Node *link;
};
class LinkedQueue//链式队列
{
private:
Node *front,*rear;//队头、队尾指针
public:
LinkedQueue(){rear=NULL;front=NULL;}//构造函数
~LinkedQueue(){makeEmpty();}//析构函数
bool EnQueue(const int& x);//将x加入队列中
bool DeQueue();//删除队头元素
bool GetFront(int& x)const;//查看队头元素的值
void makeEmpty();//置空队列
bool IsEmpty()const{return(front==NULL)?true:false;}//判断队列是否为空
int getSize()const;//求队列中的元素个数
void baoshu();//报数重新排列
friend ostream& operator<<(ostream& os,LinkedQueue& Q);//输出队列中元素的重载操作<<
};
void LinkedQueue::makeEmpty(){//置空队列,释放链表中所有结点
Node *p;
while(front!=NULL){//逐个删除队列中的结点
p=front;
front=front->link;
delete p;
}
}
bool LinkedQueue::EnQueue(const int& x){//将新元素x插入到队列的队尾
if(front==NULL){//空队列时,新结点成为队列的第一个结点,既是队头又是队尾
front=rear=new Node;
front->data=x;
rear->data=x;
rear->link=NULL;
if(front==NULL)//分配结点失败
return false;
}
else{//非空队列时,在队尾追加新的结点并更新队尾指针
rear->link=new Node;
rear->link->data=x;
if(rear->link==NULL)//分配结点失败
return false;
rear=rear->link;
rear->link=NULL;
}
return true;
}
bool LinkedQueue::DeQueue(){//如果队列不为空,将队头结点从链式队列中删去
if(IsEmpty()==true)return false;
Node *p=front;
//x=front->data;
front=front->link;
delete p;
return true;
}
bool LinkedQueue::GetFront(int &x)const{//若队列不为空,则函数返回队头元素的值及true。若队列为空,返回false
if(IsEmpty()==true)return false;
x=front->data;
return true;
}
int LinkedQueue::getSize()const{//求队列元素个数
Node *p=front;
int count=0;
while(p!=NULL){
p=p->link;
count++;
}
return count;
}
void LinkedQueue::baoshu(){//报数重新排列
int i=0,j=0;
Node *p=front,*q=front;
LinkedQueue Q1;
while(p!=NULL){//单数情况
i++;
if(i%2!=0){
Q1.EnQueue(p->data);
}
p=p->link;
}
while(q!=NULL){//双数情况
j++;
if(j%2==0){
Q1.EnQueue(q->data);
}
q=q->link;
}
cout<<Q1<<endl;
}
ostream& operator<<(ostream& os,LinkedQueue& Q){//输出队列中元素的重载操作<<
os<<"队列中元素个数有"<<Q.getSize()<<endl;
cout<<"队列元素:";
Node *p=Q.front;
while(p!=NULL){
os<<p->data<<" ";
p=p->link;
}
cout<<endl;
return os;
}
int main()
{
int n,x;
LinkedQueue Q;
cout<<"请输入队列中的元素个数:"<<endl;
cin>>n;
cout<<"请输入元素值:";
for(int i=0;i<n;i++){
cin>>x;
Q.EnQueue(x);
}
cout<<Q<<endl;
Q.baoshu();
system("pause");
return 0;
}