-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
70 lines (58 loc) · 1.13 KB
/
MyQueue.java
File metadata and controls
70 lines (58 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Stack;
public class MyQueue
{
private Stack<Integer> s;
public MyQueue()
{
s = new Stack<Integer>();
}
public MyQueue(int[] x)
{
s = new Stack<Integer>();
for ( int i : x )
s.push(i);
}
// Push element x to the back of queue.
public void push(int x)
{
s.push(x);
}
// Removes the element from in front of queue.
public void pop()
{
/*/ old
System.out.print("s: ");
for ( int i = 0; i < s.size(); i++ )
System.out.print(s.get(i) + " ");
System.out.println();
*/
Stack<Integer> tmp = new Stack<Integer>();
while ( !s.isEmpty() )
tmp.push(s.pop());
tmp.pop();
while ( !tmp.isEmpty() )
s.push(tmp.pop());
/*/ new
System.out.print("s - new: ");
for ( int i = 0; i < s.size(); i++ )
System.out.print(s.get(i) + " ");
System.out.println();
*/
}
// Get the front element.
public int peek()
{
Stack<Integer> tmp = new Stack<Integer>();
while ( !s.isEmpty() )
tmp.push(s.pop());
int ret = tmp.peek();
while ( !tmp.isEmpty() )
s.push(tmp.pop());
return ret;
}
// Return whether the queue is empty.
public boolean empty()
{
return s.isEmpty();
}
}