From 19b745215b3bc1bd19c84688a15f1814912494e0 Mon Sep 17 00:00:00 2001 From: sahilb2 Date: Fri, 27 Oct 2017 12:40:50 -0500 Subject: [PATCH] added peek function for the queue --- Others/QueueUsingTwoStacks.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java index 19550df8faa4..d932f2728830 100644 --- a/Others/QueueUsingTwoStacks.java +++ b/Others/QueueUsingTwoStacks.java @@ -55,6 +55,21 @@ public Object remove() { 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 * @@ -101,18 +116,24 @@ public static void main(String args[]){ // outStack: [(top) 2, 3, 4] myQueue.insert(5); + System.out.println(myQueue.peek()); //Will print 2 // instack: [(top) 5] // outStack: [(top) 2, 3, 4] myQueue.remove(); + System.out.println(myQueue.peek()); //Will print 3 // instack: [(top) 5] // outStack: [(top) 3, 4] myQueue.remove(); + System.out.println(myQueue.peek()); //Will print 4 // instack: [(top) 5] // outStack: [(top) 4] myQueue.remove(); // instack: [(top) 5] // outStack: [] + System.out.println(myQueue.peek()); //Will print 5 + // instack: [] + // outStack: [(top) 5] myQueue.remove(); // instack: [] // outStack: [] 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