A queue is a common data structure that can be viewed as a special linear table that follows the FIFO principle. In Java, LinkedList implements the queue interface because LinkedList is more efficient at inserting and deleting operations
Related Common methods:
Boolean offer (E): Appends the element to the end of the queue and returns true if the addition succeeds.
E poll (): Removes and returns the element from the first team.
E Peek (): Returns the first element of the team, but does not delete
Example code:
Public classQueuedemo { Public Static voidMain (String [] args) {queue<string>Queue=NewLinkedlist<string> ();//Append element Queue. Offer ("One");Queue. Offer ("both");Queue. Offer ("three");Queue. Offer ("Four"); System.out.println (Queue);//Remove elements from the first team and deleteString poll =Queue. Poll (); System.out.println (poll); System.out.println (Queue);//Remove elements from first team but do not deleteString peek =Queue. Peek (); SYSTEM.OUT.PRINTLN (Peek); System.out.println (Queue);//Traversal queue, it is important to note that each time the element is removed, the entire //queue will be shortened, so only the size of the queue can be determined while(Queue. Size () >0) {System.out.println (Queue. poll ()); } }}
Operation Result:
[One, one, three, four]
One
[Three, four]
Both
[Three, four]
Both
Three
Four
Two-way Queue (Deque), is a sub-interface of the queue, the two-way queue is that the elements at both ends of the queues can be queued (offer) can also be out of the team (poll), if the Deque limit to only from one end to queue and out of the team, you can implement the data structure of the stack. For stacks, there is a stack (push) and a stack (pop), followed by the advanced post-out principle
Common methods are as follows:
void push (E E): pushes the given element into the stack. The deposited element will be at the top of the stack. That is: The first element of a stack
E pop (): Deletes and returns the first element of the stack.
Example code:
Public classDequedemo { Public Static void Main(string[] args) {Deque<string> Deque =NewLinkedlist<string> (); Deque.push ("a"); Deque.push ("B"); Deque.push ("C"); System. out. println (Deque);the element does not stack after getting the first element of the stackString str = Deque.peek (); System. out. println (str); System. out. println (Deque); while(Deque.size () >0) {//Get stack first element, the element will be out of the stackSystem. out. println (Deque.pop ()); } System. out. println (Deque); }}
Operation Result:
[C, B, a]
C
[C, B, a]
C
B
A
[]
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Queue and Deque in Java