Queue and deque in Java, Javaqueuedeque
A queue is a common data structure. It can be viewed as a special linear table. This structure follows the first-in-first-out principle. In Java, the Queue List implements the Queue interface, because the Queue list is highly efficient in insert and delete operations.
Common Methods:
Boolean offer (E e): append an element to the end of the queue. If the addition is successful, true is returned.
E poll (): deletes the element from the beginning of the queue and returns the element.
E peek (): returns the first element of the team, but does not delete it.
Sample Code:
Public class QueueDemo {public static void main (String [] args) {Queue <String> queue = new queue list <String> (); // append the Queue element. offer ("one"); queue. offer ("two"); queue. offer ("three"); queue. offer ("four"); System. out. println (queue); // extracts elements from the beginning of the queue and deletes String poll = queue. poll (); System. out. println (poll); System. out. println (queue); // extracts elements from the beginning of the queue but does not delete String peek = queue. peek (); System. out. println (peek); System. out. println (queue); // traverses the queue. Note that each element is deleted, and the entire queue is shortened. Therefore, you only need to determine the queue size while (queue. size ()> 0) {System. out. println (queue. poll ());}}}
Running result:
[One, two, three, four]
One
[Two, three, four]
Two
[Two, three, four]
Two
Three
Four
A two-way Queue (Deque) is a sub-interface of the Queue. A two-way Queue means that the elements at both ends of the Queue can be either in the Queue (offer) or out of the Queue (poll ), if Deque is restricted to only one end of the queue and the data structure of the stack can be implemented. For the stack, there are push and pop, follow the advanced post-release Principle
The common method is as follows:
Void push (E): pushes a given element to the stack. The stored elements are at the beginning of the stack. That is, the first element of the stack.
E pop (): deletes the first element of the stack and returns it.
Sample Code:
Public class DequeDemo {public static void main (String [] args) {Deque <String> deque = new shortlist <String> (); deque. push ("a"); deque. push ("B"); deque. push ("c"); System. out. println (deque); // after obtaining the first element of the stack, the element will not output the stack String str = deque. peek (); System. out. println (str); System. out. println (deque); while (deque. size ()> 0) {// after obtaining the first element of the stack, the element will go out of the stack System. out. println (deque. pop ();} System. out. println (deque );}}
Running result:
[C, B, a]
C
[C, B, a]
C
B
A
[]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.