File tree 1 file changed +21
-0
lines changed
1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -55,6 +55,21 @@ public Object remove() {
55
55
return this .outStack .pop ();
56
56
}
57
57
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
+
58
73
/**
59
74
* Returns true if the queue is empty
60
75
*
@@ -101,18 +116,24 @@ public static void main(String args[]){
101
116
// outStack: [(top) 2, 3, 4]
102
117
103
118
myQueue .insert (5 );
119
+ System .out .println (myQueue .peek ()); //Will print 2
104
120
// instack: [(top) 5]
105
121
// outStack: [(top) 2, 3, 4]
106
122
107
123
myQueue .remove ();
124
+ System .out .println (myQueue .peek ()); //Will print 3
108
125
// instack: [(top) 5]
109
126
// outStack: [(top) 3, 4]
110
127
myQueue .remove ();
128
+ System .out .println (myQueue .peek ()); //Will print 4
111
129
// instack: [(top) 5]
112
130
// outStack: [(top) 4]
113
131
myQueue .remove ();
114
132
// instack: [(top) 5]
115
133
// outStack: []
134
+ System .out .println (myQueue .peek ()); //Will print 5
135
+ // instack: []
136
+ // outStack: [(top) 5]
116
137
myQueue .remove ();
117
138
// instack: []
118
139
// outStack: []
You can’t perform that action at this time.
0 commit comments