This repository was archived by the owner on Aug 16, 2020. It is now read-only.
File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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: []
You can’t perform that action at this time.
0 commit comments