数据结构与算法题目集7-18 银行业务队列简单模拟(c语言实现)

原题链接
很基本的一道队列的应用,因为数据量较少,其实可以直接用顺序队列做,下面我们分别给出链队列和顺序队列两种解法:
链队列:

#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++]);
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值