原题链接
很基本的一道队列的应用,因为数据量较少,其实可以直接用顺序队列做,下面我们分别给出链队列和顺序队列两种解法:
链队列:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
struct node* next;
int data;
}lqnode;
typedef struct{
struct node* front;
struct node* rear;
}lqueue;
void lqueueinit(lqueue *q){
q->front=NULL;
q->rear=NULL;
}
void lqueueappend(lqueue *q,int x){
lqnode *p;
p=(lqnode *)malloc(sizeof(lqnode));
p->next=NULL;
p->data=x;
if(q->rear!=NULL){
q->rear->next=p;
}
q->rear=p;
if(q->front==NULL){
q->front=p;
}
}
int lqueuedelete(lqueue *q,int *x){
lqnode *p=q->front;
if(q->front==NULL){
return 0;
}else{
*x=p->data;
q->front=q->front->next;
if(q->front==NULL){
q->rear=NULL;
}
free(p);
return 1;
}
}
int lqueuenotempty(lqueue q){
if(q.front==NULL){
return 0;
}else{
return 1;
}
}
int main(){
lqueue q1,q2;
lqueueinit(&q1);
lqueueinit(&q2);
int n,i,p;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&p);
if(p%2==0){
lqueueappend(&q2,p);
}else{
lqueueappend(&q1,p);
}
}
int j=1,m,t=0;
while(lqueuenotempty(q1) || lqueuenotempty(q2)){
if(lqueuenotempty(q1)){
lqueuedelete(&q1,&m);
if(t==0){
printf("%d",m);
t=1;
}else{
printf(" %d",m);
}
}
if(lqueuenotempty(q2)){
if(j==2){
lqueuedelete(&q2,&m);
if(t==0){
printf("%d",m);
t=1;
}else{
printf(" %d",m);
}
j=1;
}else{
j++;
}
}
}
}
顺序队列:
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,j,rear1=0,front1=0,t,front2=0,rear2=0;
scanf("%d",&n);
int js[n],os[n];
for(i=0;i<n;i++){
scanf("%d",&t);
if(t%2==0){
os[rear2++]=t;
}else{
js[rear1++]=t;
}
}
i=1;
t=1;
while(rear1!=front1 && rear2!=front2){
if(i && t){
printf("%d",js[front1++]);
t=0;
}else if(i==1){
printf(" %d",js[front1++]);
}else{
printf(" %d",js[front1++]);
printf(" %d",os[front2++]);
}
if(i==1){
i++;
}else{
i=1;
}
}
if(rear1==front1){
while(rear2!=front2){
if(t){
printf("%d",os[front2++]);
t=0;
}else{
printf(" %d",os[front2++]);
}
}
}else{
while(rear1!=front1){
if(t){
printf("%d",js[front1++]);
t=0;
}else{
printf(" %d",js[front1++]);
}
}
}
}