The queue is the basic data structure that every coder must master.
The queue is logically like a long line of rice, preceded by a first-served meal (FIFO).
Here an array is used to construct a queue and set two points, head pointing to the team head, tail pointing to the tail, the initial state is head and tail pointing to the same position (queue is empty)
The queue has two operations: Team up and out.
1. Team: Compared to the scene of the rice queue, the new person is in the back, this is the tail tail need to move back one.
2. Team: The person who has already cooked the meal can go out, then the team head also need to move back one, let the people behind become team head.
Attention:
What if head and tail are moved to the end of the array?
Although the array is logically empty, there is no way to queue up!
So we need to take out the idea of a circle, and think of the array as a space without a limit, that is, the last one in the array is the first (how to make head and tail from the end of the array into a header?). Take-up operation).
So if the queue is full of how to determine: Tail after a point to the head, then the full (because after the head, tail before the space is now occupied, the two spaces are connected)
The code is as follows:
#include <iostream>using namespacestd;//Queue Array/*Queue Array Optimization scheme: In order to ensure that the array space is fully utilized, the first end position of the array can be set to the first end position of the queue instead of the first end point: Head,tail; the array is treated as a space connected by the first head, and the head of the tail points to the tail if he AD and tail point to the same location, then the queue is empty if head is in a position before tail, it indicates that the queue is full*/inta[Ten];intHead =0;intTail =0; voidInsertintvalue) { inttemp = (tail+1)%Ten; if(temp==head) { Throw "Queue full Error"; } A[tail]=value; Tail=temp;}intdequeue () {if(Tail = =head) { Throw "Queue empty Error"; } intValue =A[head]; Head= (head+1)%Ten; returnvalue;}intMain () { while(1) {cout<<"here is a queue structure, 1. Enqueue, 2. Team"<<endl<<"Please enter:"; int Select; CIN>>Select; if(Select==1) {cout<<"Please enter the queue value:"; intvalue; CIN>>value; Insert (value); } Else{cout<<"the first team:"<<dequeue () <<Endl; } } return 0;}
Build queue, array version