Andy897
Andy897

Reputation: 7133

Why first peek and then remove instead of poll

At multiple instances, I came across algorithms where first queue head is peeked and then removed. I was wondering if there is any particular reason why poll is not used instead. For example the following algorithm for level order traversal of a binary tree HERE

  1. Add the root node to the queue.
  2. Assign queue size to a variable, say count. Repeat step 3 to 7 count times, where N is the size of the queue.
  3. If the queue is not empty, print out the queue.
  4. Peek the head node
  5. If the head has left child, add it to the queue
  6. If the head has right child, add it to the queue
  7. Remove the head from the queue.
  8. If the queue is not empty, go back to step 2.

Upvotes: 2

Views: 309

Answers (4)

Henrik
Henrik

Reputation: 23324

Some containers only offer peek and remove, because with a function that does both, it's hard or impossible to give the strong exception guarantee: http://en.wikipedia.org/wiki/Exception_safety

Upvotes: 4

Walt
Walt

Reputation: 1436

peek : Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

poll : Retrieves and removes the head of this queue, or returns null if this queue is empty.

remove : Retrieves and removes the head of this queue.

Upvotes: 1

Elektron
Elektron

Reputation: 15

Peek retrieves the element at the back of the queue (last element) without deleting it, so PEEKing is a good way to view that element to confirm if it's what you want to modify. You already know pop would remove the element without giving you a reference to the element to check it. SO it actually depends on what you really want to do.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

You can peek an element, test it and possibly decide not to remove it

Upvotes: 0

Related Questions