说明:
利用队列进行排序,将舞伴进行相应的排序。
实例:
男:ZhangSan LiSi WangWU
女:LiLi LiHua WangHua ZhangMeng ZhaoHua
输出:
ZhangSan LiLi LiSi LiHua WangWU WangHua
queue.h
#ifndef queue_h__
#define queue_h__
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct{
char sex;
char name[256];
} ElementType;
enum boolean {FALSE, TRUE};
typedef enum boolean BOOL;
typedef struct queue_def{
ElementType* elementtype;
int rear;
int front;
int MaxSize;
}queue;
void initQueue(queue* q, int sz);
void freeQueue(queue* q);
void MakeEmpty(queue* q);
BOOL isEmpty(queue q);
BOOL isFull(queue q);
int Length(queue q);
BOOL enQueue(queue* q, ElementType e);
BOOL deQueue(queue *q, ElementType* e);
ElementType getFront(queue q);
#endif // queue_h__
queue.c
#include "queue.h"
void initQueue(queue* q, int sz){
if (sz < 0){
puts("error: sz < 0");
exit(1);
}
else{
q->MaxSize = sz +1 ;
q->front = q->rear = 0;
q->elementtype = (ElementType*)malloc(q->MaxSize*sizeof(ElementType));
if (!q->elementtype){
puts("error: malloc error!");
exit(1);
}
}
}
void freeQueue(queue* q){
free(q->elementtype);
}
void MakeEmpty(queue* q){
q->front = q->rear = 0;
}
BOOL isEmpty(queue q){
return (BOOL)(q.front == q.rear);
}
BOOL isFull(queue q){
return(BOOL)(q.front==(q.rear+1)%q.MaxSize);
}
int Length(queue q){
return (q.rear-q.front+q.MaxSize);
}
BOOL enQueue(queue* q, ElementType e){
if (!isFull(*q)){
q->elementtype[q->rear] = e;
q->rear = (q->rear+1)%q->MaxSize;
}
else{
puts("error: enQueue,FULL!");
exit(1);
}
return TRUE;
}
BOOL deQueue(queue *q, ElementType* e){
if (!isEmpty(*q)){
*e = q->elementtype[q->front];
q->front = (q->front+1)%q->MaxSize;
}
else{
puts("error: deQueue,empty!!");
exit(1);
}
return TRUE;
}
ElementType getFront(queue q){
if (isEmpty(q)){
puts("error:getFromt, empty!!");
exit(1);
}
return q.elementtype[q.front];
}
main.c
#include <string.h>
#include "queue.h"
void process();
int main(){
process();
return 0;
}
void process(){
ElementType m[3] = {{'M', "ZhangSan"}, {'M', "LiSi"}, {'M', "WangWU"}};
ElementType f[5] = {{'F', "LiLi"}, {'F', "LiHua"},{'F', "WangHua"}, {'F', "ZhangMeng"}, {'F', "ZhaoHua"}};
queue q_m, q_f;
ElementType t;
char name_m[256], name_f[256];
int i, j;
initQueue(&q_m, 3);
initQueue(&q_f, 5);
for (i=0; i<3; i++)
enQueue(&q_m, m[i]);
for (i=0; i<5; i++)
enQueue(&q_f, f[i]);
while (!isEmpty(q_f) && !isEmpty(q_m)){
deQueue(&q_m, &t);
strcpy(name_m, t.name);
deQueue(&q_f, &t);
strcpy(name_f, t.name);
printf("%s %s
", name_f, name_m);
}
}