1.顺序队列(c++模板类实现)
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1e5 + 10;
template<typename T>
class Queue
{
private:
int en;
int be;
T *base;
public:
void Init()
{
be=en=0;
base=new T[maxn];
}
void Push(T num)
{
base[en]=num;
en=(en+1)%maxn;
}
int Empty()//此情况是在队列没有满的前提下
{
if(en==be)
return 1;
return 0;
}
T Front()
{
return base[be];
}
int Length()
{
return (en-be+maxn)%maxn;
}
void Pop()
{
be=(be+1)%maxn;
}
};
int main()
{
Queue<int> a;
Queue<int> b;
a.Init();
b.Init();
int t;
int n;
cin>>t;
vector<int> ans;
while(t--){
cin>>n;
if(n%2==1)
a.Push(n);
else
b.Push(n);
// cout<<"aaaaaaa"<<endl;
}
//cout<<"--------------"<<endl;
while(!a.Empty()&&!b.Empty())
{
if(!a.Empty())
{
ans.push_back(a.Front());
a.Pop();
}
if(!a.Empty())
{
ans.push_back(a.Front());
a.Pop();
}
if(!b.Empty())
{
ans.push_back(b.Front());
b.Pop();
}
}
while(!a.Empty())
{
ans.push_back(a.Front());
a.Pop();
}
while(!b.Empty())
{
ans.push_back(b.Front());
b.Pop();
}
for(int i=0;i<ans.size();i++)
{
if(i)
cout<<" ";
cout<<ans[i];
}
cout<<endl;
}
2.链式队列
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
const int maxn = 1e5;
typedef struct Qnode
{
int data;
struct Qnode *next;
}Qnode,*QnodePointer;
typedef struct ListQueue
{
QnodePointer be;
QnodePointer en;
}ListQueue;
void Init(ListQueue &L)
{
L.be=(QnodePointer)malloc(sizeof(Qnode));
L.en=L.be;
// L.en=(QnodePointer)malloc(sizeof(Qnode));
L.be->next=NULL;
}
void Destroy(ListQueue &L)
{
while(L.be){
QnodePointer p=L.be->next;
free(L.be);
L.be=p;
}
}
void Push(ListQueue &L,int n)
{
QnodePointer p=(QnodePointer)malloc(sizeof(Qnode));
p->data=n;
p->next=NULL;
L.en->next=p;
L.en=p;
}
int Front(ListQueue &L)
{
return L.be->next->data;
}
void Pop(ListQueue& L)
{
QnodePointer p=L.be->next;
L.be->next=p->next;
if(L.en==p)
L.en=L.be;
free(p);
}
int Empty(ListQueue &L)
{
if(L.be==L.en)
return 1;
return 0;
}
int main()
{
int t;
int n;
int ans[100010];
ListQueue a;
ListQueue b;
Init(a);
Init(b);
scanf("%d",&t);
//printf("--------------------\n");
while(t--)
{
scanf("%d",&n);
if(n%2){
Push(a,n);
//cout<<a.be->next->data<<" "<<a.en->data<<"aaaaaa"<<endl;
}
else{
Push(b,n);
// cout<<b.be->next->data<<" "<<b.en->data<<"bbbbb"<<endl;
}
}
//printf("---===============\n");
int len=0;
while(!Empty(a)&&!Empty(b))
{
if(!Empty(a))
{
ans[len++]=Front(a);
// cout<<ans[len-1]<<"hahahah"<<endl;
Pop(a);
}
//if(Empty(a))
// cout<<"Empty A"<<endl;
if(!Empty(a))
{
ans[len++]=Front(a);
Pop(a);
}
if(!Empty(b))
{
ans[len++]=Front(b);
Pop(b);
}
// printf("ssjdksjdksjdksjdksjdksjdks]\n");
}
while(!Empty(a)){
ans[len++]=Front(a);
Pop(a);
}
while(!Empty(b))
{
ans[len++]=Front(b);
Pop(b);
}
int i=0;
//cout<<len<<"========="<<endl;
for(i=0;i<len;i++)
{
if(i)
printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}