Merge pull request #282 from sahilb2/master
Added "peek" function for QueueUsingTwoStacks
This commit is contained in:
commit
962720fc6b
@ -55,6 +55,21 @@ class QueueWithStack {
|
|||||||
return this.outStack.pop();
|
return this.outStack.pop();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Peek at the element from the front of the queue
|
||||||
|
*
|
||||||
|
* @return the new front of the queue
|
||||||
|
*/
|
||||||
|
public Object peek() {
|
||||||
|
if(this.outStack.isEmpty()) {
|
||||||
|
// Move all elements from inStack to outStack (preserving the order)
|
||||||
|
while(!this.inStack.isEmpty()) {
|
||||||
|
this.outStack.push( this.inStack.pop() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.outStack.peek();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if the queue is empty
|
* Returns true if the queue is empty
|
||||||
*
|
*
|
||||||
@ -101,18 +116,24 @@ public class QueueUsingTwoStacks {
|
|||||||
// outStack: [(top) 2, 3, 4]
|
// outStack: [(top) 2, 3, 4]
|
||||||
|
|
||||||
myQueue.insert(5);
|
myQueue.insert(5);
|
||||||
|
System.out.println(myQueue.peek()); //Will print 2
|
||||||
// instack: [(top) 5]
|
// instack: [(top) 5]
|
||||||
// outStack: [(top) 2, 3, 4]
|
// outStack: [(top) 2, 3, 4]
|
||||||
|
|
||||||
myQueue.remove();
|
myQueue.remove();
|
||||||
|
System.out.println(myQueue.peek()); //Will print 3
|
||||||
// instack: [(top) 5]
|
// instack: [(top) 5]
|
||||||
// outStack: [(top) 3, 4]
|
// outStack: [(top) 3, 4]
|
||||||
myQueue.remove();
|
myQueue.remove();
|
||||||
|
System.out.println(myQueue.peek()); //Will print 4
|
||||||
// instack: [(top) 5]
|
// instack: [(top) 5]
|
||||||
// outStack: [(top) 4]
|
// outStack: [(top) 4]
|
||||||
myQueue.remove();
|
myQueue.remove();
|
||||||
// instack: [(top) 5]
|
// instack: [(top) 5]
|
||||||
// outStack: []
|
// outStack: []
|
||||||
|
System.out.println(myQueue.peek()); //Will print 5
|
||||||
|
// instack: []
|
||||||
|
// outStack: [(top) 5]
|
||||||
myQueue.remove();
|
myQueue.remove();
|
||||||
// instack: []
|
// instack: []
|
||||||
// outStack: []
|
// outStack: []
|
||||||
|
Loading…
Reference in New Issue
Block a user