[Level 1: Basic operation of queue based on circular linked list] [Programming training - queue] [Touge] [bjfu246]

mission details

The task of this level: Use a circular linked list with the leading node to represent the queue, and only set a pointer to the element node at the end of the queue (no head pointer). Implement the enqueue and dequeue of the queue and determine whether the queue is empty.

programming requirements

Enter
multiple sets of data, each set of data has two rows. The first line is two integers n and m, n represents the length of the enqueuing sequence A (n numbers are successively enqueued, and there is no case of leaving the queue in the middle), m represents the number of elements in the queue sequence B (m numbers are sequentially continuous Out of the team, there is no enqueue in the middle). The second line is the sequence A (space-separated n integers). When both n and m are equal to 0, the input ends.

Output
Output one line for each set of data. Each line includes m+1 integers, the first m numbers represent each integer of the dequeue sequence B, and the last integer indicates whether the queue is empty, output 0 if the queue is empty, and output 1 if it is not empty. Integers are separated by spaces.

Test instructions
The platform will test the code you write:

Test input:
5 3
1 3 5 3 6
4 4
-1 2 3 4
0 0

Expected output:
1 3 5 1
-1 2 3 4 0

C++ code:

head. h
see notes for details

#include<iostream>
using namespace std;
typedef struct QNode
{
    
    //队列的链式存储结构
    int data;
    struct QNode* next;
}QNode, * QueuePtr;
typedef struct
{
    
    
    QueuePtr rear;    //只设一个队尾指针
}LinkQueue;
int EmptyQueue(LinkQueue Q)
{
    
    //判断队列是否为空,空返回1,否则返回0
//队列只有一个头结点,即当头结点的指针域指向自己时,队列为空
  return(Q.rear->next->next==Q.rear->next)?1:0;
}
void EnQueue(LinkQueue& Q, int e)
{
    
    //入队,插入元素e为Q的新的队尾元素
       QNode *p=new QNode;
        p->data=e;
        p->next=Q.rear->next;
        Q.rear->next=p;
        Q.rear=p;
}
void DeQueue(LinkQueue& Q)
{
    
    //出队,输出Q的队头元素值,后将其删除
   QNode *p=Q.rear->next->next;
        printf("%d ",p->data);
        if(p==Q.rear)
        {
    
    
            Q.rear=Q.rear->next;
            Q.rear->next=p->next;
        }
        else Q.rear->next->next=p->next;
        delete p;
}

The main function file is not editable:

#include "head.h"
int main()
{
    
    
	int n,m;
	while(cin>>n>>m)
	{
    
    
		if(n==0&&m==0) break;
		LinkQueue Q;        //初始化一个带头结点的循环链表
		Q.rear=new QNode;
        Q.rear->next=Q.rear;
		while(n--)
		{
    
    
			int e;cin>>e;
			EnQueue(Q,e);
		}
		while(m--)
			DeQueue(Q);
		if(EmptyQueue(Q))
			cout<<"0"<<endl;
		else
			cout<<"1"<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/Tommy_Nike/article/details/127831490