Reputation: 7133
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
Upvotes: 2
Views: 309
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
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
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
Reputation: 136062
You can peek an element, test it and possibly decide not to remove it
Upvotes: 0