Repository navigation
Expand file tree
/
Copy pathQueueUsingStacks.java
More file actions
83 lines (68 loc) · 1.66 KB
/
Copy pathQueueUsingStacks.java
File metadata and controls
83 lines (68 loc) · 1.66 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
71
72
73
74
75
76
77
78
79
80
81
82
83
package LeetCode;
import java.util.Stack;
import LeetCode.LevelOrderTraversal.TreeNode;
public class QueueUsingStacks {
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public static void main(String args[]) throws Exception
{
push(1);
push(2);
System.out.println(peek());
push(3);
System.out.println(peek());
/* push(2);
System.out.println(peek());
pop();
push(3);
push(4);
push(5);
pop();
pop();
System.out.println(peek());
*/
}
// Push element x to the back of queue.
public static void push(int x) {
// Make the dequeue operation costly
// The enqueue operation should not be made costly
stack1.push(x);
}
// Removes the element from in front of queue.
public static void pop() {
// Trannsfer all elements from the elements from stack1 to stack2
if (stack2.isEmpty())
{
while(!stack1.isEmpty())
{
int element = stack1.pop();
stack2.push(element);
}
}
stack2.pop();
}
// Get the front element.
public static int peek() {
if (stack2.isEmpty())
{
// Trannsfer all elements from the elements from stack1 to stack2
while(!stack1.isEmpty())
{
int element = stack1.pop();
stack2.push(element);
}
}
return stack2.peek();
}
// Return whether the queue is empty.
public static boolean empty() {
if (stack1.isEmpty() && stack2.isEmpty())
{
return true;
}
else
{
return false;
}
}
}