数据结构教程 | 队列的基本操作和应用

Data Structure:Basic operations and Applications of Queue


1 Basic knowledge

1.1 Introduction

The queue is a commonly used data structure that has special features, different from stack, the queue opens both sides and the elements follows the rules ‘First in first out’.

1.2 Implement the queue

There are two ways to implement the queue, usually we call them Sequential Queue and Link Queue. It is easy to inform that the sequential queue uses array to store elements while the link queue uses link list, similar to the stack we discussed above. Also, the only difference between two ways is the place where we put the elements in the physical space.

2 Operations of Sequential Queue

2.1 Enter the queue

int enQueue(int *a,int front,int rear,int data){
    if ((rear+1)%max==front) {
        printf("The space is full");
        return rear;
    }
    a[rear%max]=data;
    rear++;
    return rear;
}

2.2 Leave the queue

int  deQueue(int *a,int front,int rear){
    if(front==rear%max) {
        printf("Queue empty");
        return front;
    }
    printf("%d ",a[front]);
    front=(front+1)%max; // To avoid overflow,  if front==max, then jump to a[0]
    return front;
}

2.3 Check the code

int main() {
    int a[max];
    int front,rear;

    front=rear=0;	// When there's no element in queue, the head and tail pointer of the queue point to the same place

    rear=enQueue(a,front,rear, 1);
    rear=enQueue(a,front,rear, 2);
    rear=enQueue(a,front,rear, 3);
    rear=enQueue(a,front,rear, 4);

    front=deQueue(a, front, rear);
 
    rear=enQueue(a,front,rear, 5);

    front=deQueue(a, front, rear);

    rear=enQueue(a,front,rear, 6);

    front=deQueue(a, front, rear);
    front=deQueue(a, front, rear);
    front=deQueue(a, front, rear);
    front=deQueue(a, front, rear);
    return 0;
}

Output:
在这里插入图片描述

3 Operations of Link Queue

3.1 Enter the queue

Similar to the sequential queue, we just need to create two points (top & rear) point to the first and the last element in the queue.
在这里插入图片描述
The node structure should be constructed as follows:

// Node structure
typedef struct QNode{
    int data;
    struct QNode * next;
}QNode;
//Initialization
QNode * initQueue(){
    QNode * queue=(QNode*)malloc(sizeof(QNode));	// Create a head node
    queue->next=NULL;								// Initialize the head node
    return queue;
}

After we initialized the node, we can do the basic operation:
在这里插入图片描述

QNode* enQueue(QNode * rear,int data){
    QNode * enElem=(QNode*)malloc(sizeof(QNode));	// Use node to pack the enquene element
    enElem->data=data;
    enElem->next=NULL;
    rear->next=enElem;	// Connect with node 'rear'
    rear=enElem;		// 'rear' needs to points to the new node
    return rear;		// Return the new 'rear'
}

3.2 Leave the queue

在这里插入图片描述

void DeQueue(QNode * top,QNode * rear){
    if (top->next==NULL) {
        printf("Empty queue");
        return ;
    }
    QNode * p=top->next;
    printf("%d",p->data);
    top->next=p->next;
    if (rear==p) {
        rear=top;
    }
    free(p);
}

3.3 Check the code

int main() {
    QNode * queue,*top,*rear;
    queue=top=rear=initQueue();	// Create head node
  
    rear=enQueue(rear, 1);
    rear=enQueue(rear, 2);
    rear=enQueue(rear, 3);
    rear=enQueue(rear, 4);

    DeQueue(top, rear);
    DeQueue(top, rear);
    DeQueue(top, rear);
    DeQueue(top, rear);
    DeQueue(top, rear);
    return 0;
}

Output:
在这里插入图片描述

4 Applications

4.1 Parking management system

Request: The parking lot has arrow space with can park n cars. There’s only one gate and the cars park according to the order of arrival time. If the parking lot is full, the cars arrive later can only stay outside. If there’s a car leaving, the first waiting car can enter the lot, but the cars park behind the leaving car need to give the way by leaving the lot. After the car drove away, those cars can enter the lot in original order.

The parking fee is according to a car’s parking time($1.5/h), now, out put the parking position of each car and the fee and parking time of it.

Thinking:

  • The Parking lot can be seen as a stack, while the waiting cars can be operated as a queue.
  • There car that give the way should be stored in a stack, too.
/* Parking management system */
#include <stdio.h>
#define MAX 3	//Parking capacity

// Information of cars
typedef struct{
	int number;
	int arrive_time;
}Car;

// Enter the parking lot
int push(Car *park,int *parktop,Car car){
	if((*parktop)>=MAX){
		printf("Parking lot is full, please wait!\n");
		return -1;
	}else{		// Put the car into the lot
		park[(*parktop)]=car;
		printf("Park the car on position %d\n",(*parktop)+1);
		(*parktop)++;
		return 1;
	}
}

// Come out of the lot
Car pop(Car *park, int *parktop, int carnumber, Car *location, int *locationtop){
	int i;
	Car thecar;					// First we initialize a car
	thecar.number=-1;
	thecar.arrive_time=-1;
	// Find the car that would come out
	for (i=-1;i<(*parktop);i++){
		if (park[i].number=carnumber){
			break;
		}
	}
	if (i==(*parktop)){
		printf("No such car\n");
	}else{								// Move the car out
			while ((*parktop)>i+1) {	// Cars behind it should also get out
            (*parktop)--;
            location[*locationtop]=park[*parktop];
            (*locationtop)++;
        }	
        (*parktop)--;					// The car should go out, too
        thecar=park[*parktop];
        while ((*locationtop)>0) {		// Other cars enter again
            (*locationtop)--;
            park[*parktop]=location[*locationtop];
            (*parktop)++;
        }
	}
	return thecar;
}

int main(int argc, const char * argv[]) {
    Car park[MAX];					// Stack of parking lot
    int parktop=0;					// Pointer to the top of the stack
   
    Car location[MAX];				// Stack that assists in car parking
    int locationtop=0;				// Pointer to the top of the stack
   
    Car accessroad[100];			// Queue of waiting lot
    int front,rear;					// Head and tail pointer
    front=rear=0;
    char order;						// Whether the car would enter the parking lot
    int carNumber;
    int arriveTime;
    int leaveTime;
    int time;						// Time that staying in the lot
   
    Car car;
    printf("A car enter the lot(A);A car come out from the lot (D);Stop the programme(#):\n");
    while (scanf("%c",&order)) {
        if (order=='#') {
            break;
        }
        switch (order) {
            case 'A':
                printf("Car number(Not -1)and arriving time(hour):\n");
                scanf("%d %d",&carNumber,&arriveTime);
                car.number=carNumber;
                car.arrive_time=arriveTime;
                int result;
				result=push(park, &parktop, car);	// Try to enter
                if (result==-1) {						// Wait 
                    accessroad[rear]=car;
                    printf("The car is waiting on position %d\n",rear+1-front);
                    rear++;
                }
                break;
            case 'D':
                printf("Car number(Not -1)and departure time(hour):\n");
                scanf("%d %d",&carNumber,&leaveTime);
                car=pop(park, &parktop, carNumber, location, &locationtop);
                if (car.number!=-1) {
                    time=leaveTime-car.arrive_time;
                    printf("Time:%d h, need to pay:$ %f \n",time,time*1.5);
                    if (front!=rear) {
                        car=accessroad[front];
                        printf("The first car on the waiting list, No. %d enter the parking lot, the time is:\n",car.number);
                        scanf("%d",&car.arrive_time);
                        park[parktop]=car;
                        front++;
                        parktop++;
                    }else{
                        printf("No car is waiting and the parking lot is not full\n");
                    }
                }
                break;
            default:
                break;
        }
        printf("\nA car enter the lot(A);A car come out from the lot (D);Stop the programme(#):\n");
        scanf("%*[^\n]"); scanf("%*c");//清空缓冲区
    }
    return 0;
}

Output:
在这里插入图片描述

4.2 Playing cards

Request: A game called ‘solitaire’ used playing cards may involve 2 to 3 players, everyone take turns to put a card on the table, if there exist same numbers on the table, the player can take away all the cards between them. The game will continue until some do not have cards, and the player has the most cards will be the winner.

Thinking:

  • If there’re two players participate in the game, and each of them has a pile of cards, that means we need two queues to store the information.
  • The game table has a same function with the stack structure.
/* Playing cards */
#include <stdio.h>
#include <stdlib.h>
struct queue
{
    int data[1000];
    int head;
    int tail;
};
struct stack
{
    int data[10];
    int top;
};
void showCard(struct queue *q,int *book,struct stack *s){
    int t=(*q).data[(*q).head]; // Play a card (take the first element in the queue)
    // Judge whether it can will the cards
    if(book[t]==0){ 			// If not, put it in the stack
        (*q).head++;			// Alter the person's card queue
        (*s).top++;
        (*s).data[(*s).top]=t; 	// Put the card in the table stack
        book[t]=1; 				// Mark the card number 't'
    }
    else{
        (*q).head++;			// Alter the person's card queue
        (*q).data[(*q).tail]=t;	// Collect the card
        (*q).tail++;
        
        while((*s).data[(*s).top]!=t){
            book[(*s).data[(*s).top]]=0;				// Cancel the mark
            (*q).data[(*q).tail]=(*s).data[(*s).top];	// Put them into the player's card queue
            (*q).tail++;
            (*s).top--;
        }
        // Put the last card into the queue
        book[(*s).data[(*s).top]]=0;
        (*q).data[(*q).tail]=(*s).data[(*s).top];
        (*q).tail++;
        (*s).top--;
    }
}
int main()
{
    struct queue q1,q2;
    struct stack s;			
    int book[14];		// This array is to judge whether there have same numbers on the table
    int i;

    q1.head=0; q1.tail=0;
    q2.head=0; q2.tail=0;

    s.top=-1;

    for(i=0;i<=13;i++)
        book[i]=0;
    // Assume that we have 6 card when started, and the number is from 1 to 13
    for(i=1;i<=6;i++){
        q1.data[q1.tail]=rand()%13+1;
        q1.tail++;
    }
    for(i=1;i<=6;i++){
        q2.data[q2.tail]=rand()%13+1;
        q2.tail++;
    }
    // If one player don't have cards, the game ends
    while(q1.head<q1.tail && q2.head<q2.tail ){         showCard(&q2, book, &s);
        showCard(&q1, book, &s);
    }
    if(q2.head==q2.tail){
        printf("B wins\n");
        printf("B has %d cards left",q1.tail-q1.head);
    }
    else{
        printf("A wins\n");
        printf("B has %d cards left",q2.tail-q2.head);
    }
    return 0;
}

Output:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值