Skip to content

Commit 19b7452

Browse files
committed
added peek function for the queue
1 parent e438972 commit 19b7452

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Others/QueueUsingTwoStacks.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,21 @@ public Object remove() {
5555
return this.outStack.pop();
5656
}
5757

58+
/**
59+
* Peek at the element from the front of the queue
60+
*
61+
* @return the new front of the queue
62+
*/
63+
public Object peek() {
64+
if(this.outStack.isEmpty()) {
65+
// Move all elements from inStack to outStack (preserving the order)
66+
while(!this.inStack.isEmpty()) {
67+
this.outStack.push( this.inStack.pop() );
68+
}
69+
}
70+
return this.outStack.peek();
71+
}
72+
5873
/**
5974
* Returns true if the queue is empty
6075
*
@@ -101,18 +116,24 @@ public static void main(String args[]){
101116
// outStack: [(top) 2, 3, 4]
102117

103118
myQueue.insert(5);
119+
System.out.println(myQueue.peek()); //Will print 2
104120
// instack: [(top) 5]
105121
// outStack: [(top) 2, 3, 4]
106122

107123
myQueue.remove();
124+
System.out.println(myQueue.peek()); //Will print 3
108125
// instack: [(top) 5]
109126
// outStack: [(top) 3, 4]
110127
myQueue.remove();
128+
System.out.println(myQueue.peek()); //Will print 4
111129
// instack: [(top) 5]
112130
// outStack: [(top) 4]
113131
myQueue.remove();
114132
// instack: [(top) 5]
115133
// outStack: []
134+
System.out.println(myQueue.peek()); //Will print 5
135+
// instack: []
136+
// outStack: [(top) 5]
116137
myQueue.remove();
117138
// instack: []
118139
// outStack: []

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy