java data structure queue

The queue is based on the first in first out mode ( First   In First Out, FIFO for short ). The operations of the queue are:

In java:

Both offer() and add() can perform operations on the stack. The difference between them is that when the limit of the queue is exceeded, add() will directly throw an exception and wait for you to deal with it, while offer() has pre-judgment so put it back false

The pop()/remove() methods both remove the first element from the queue. The difference is that when the queue is empty, calling remove() will throw an exception and pop() will return null.

The element() and peek() methods are used to query the head element, which is the first element. Similarly, peek() returns null when the queue is empty, while element() throws an exception.

As shown in the figure: Add elements continuously at the end of the queue, and make pairs at the head of the queue.



//The following is the basic implementation of the queue
class Queue {
	private int maxSize;
	private long[] queArray;
	private int front;
	private int rear;
	private int nItems;

	public Queue(int s) {
		maxSize = s;
		queArray = new long[maxSize];
		front = 0;
		rear = -1;
		nItems = 0;
	}

	public void insert(long j) {
		if (rear == maxSize - 1)
			rear = -1;
		queArray[++rear] = j;
		nItems++;
	}

	public long remove() {
		long temp = queArray[front++];
		if (front == maxSize)
			front = 0;
		nItems--;
		return temp;
	}

	public boolean isEmpty() {
		return (nItems == 0);
	}

	public boolean isFull() {
		return (nItems == maxSize);
	}

	public int size() {
		return nItems;
	}

	public void display() {
		// TODO Auto-generated method stub
		
		if (rear >= front) {
			for (int i = front; i <= rear; i++) {
				System.out.print(queArray[i] + " ");
			}
		}
		else {
			for (int i = front; i < maxSize; i++) {
				System.out.print(queArray[i] + " ");
			}
			for (int i = 0; i <= rear; i++) {
				System.out.print(queArray[i] + " ");
			}
		}
		System.out.println();

	}
}
class QueueApp {
	public static void main(String[] args) {
		Queue theQueue = new Queue(5);
		
		theQueue.insert(10);
	        theQueue.insert(20);
		theQueue.insert(30);
	        theQueue.insert(40);
	        theQueue.insert(50);
	    
	        theQueue.display();
	  
	
		theQueue.remove();
		theQueue.remove();
		theQueue.remove();
		
		theQueue.insert(50);
		theQueue.insert(60);
		theQueue.insert(70);
		
		
		theQueue.display();
			
	}		
}

//result

10 20 30 40 50 
40 50 50 60 70 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325902804&siteId=291194637