Data structures Queue: poll, offer, element, peek

A queue is a special linear table, which allows only the front end of the table delete operation (Front), while the rear end of insertion, the table (rear). Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation. When there is no queue element, called an empty queue.

In such a queue data structure, the first insertion element will be the first element to be deleted; conversely the last inserted element will be deleted is the last element, the queue also known as " first in first out" (FIFO-first in first out) linear form.

In java5 new addition to java.util.Queue interface for common operations support queue. The interface extends the java.util.Collection interface.

Queue inherits the Collection interface

To try to avoid the add Collection () and remove () when using Queue method, add () and remove () method at the time of failure will throw an exception.

To use the offer () to add elements, using poll () to capture and removal elements.

Their advantage is based return value success, to use the element out of the front end without using element () or peek () method.

It is noteworthy that LinkedList class implements the Queue interface, so that we can put to use LinkedList as a Queue.

Queue<TreeNode> q = new LinkedList<>();

  Add to add one yuan cable if the queue is full, an exception is thrown a IIIegaISlabEepeplian
  Remove removes and returns the element head of the queue if the queue is empty, throw an exception NoSuchElementException
  element returns the element head of the queue if the queue is empty, an exception is thrown a NoSuchElementException
  offer add an element and returns true if the queue is full, false returns
  poll asked element is removed and returned to the head of the queue if the queue is empty, null is returned
  peek returns the element head of the queue if the queue is empty , null is returned
  put add an element if the queue is full, the blocking
  take to remove the head of the queue and returns the element if the queue is empty, blocked

Published 79 original articles · won praise 15 · views 60000 +

Guess you like

Origin blog.csdn.net/Jason_Lee155/article/details/104049682