forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementQueueUsingStacks.java
68 lines (54 loc) · 1.61 KB
/
ImplementQueueUsingStacks.java
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
/*
* Time Complexity - O(1) for push
* O(N) for peek and pop. However in avg case it is O(1).
* O(1) for isEmpty().
* Space Complexity - O(N) N is the number of element in the queue.
*
* Approach - Use two stacks.
* Push into firstStack or oldStack.
* For pop and peek - if secondStack is not empty, return the first element in stack.
* if not pop all elements from first stack into second stack.
* then return the first element from second stack.
* */
import java.util.Stack;
public class ImplementQueueUsingStacks {
Stack<Integer> stackNew;
Stack<Integer> stackOld;
public ImplementQueueUsingStacks() {
stackNew = new Stack<Integer>();
stackOld = new Stack<Integer>();
}
public void push(int x) {
stackOld.push(x);
}
private void transfer()
{
if(stackNew.isEmpty())
{
while(!stackOld.isEmpty())
{
stackNew.push(stackOld.pop());
}
}
}
public int pop() {
transfer();
return stackNew.pop();
}
public int peek() {
transfer();
return stackNew.peek();
}
public boolean empty() {
return stackNew.isEmpty() && stackOld.isEmpty();
}
public static void main(String args[]) {
ImplementQueueUsingStacks obj = new ImplementQueueUsingStacks();
obj.push(2);
obj.push(3);
System.out.println(obj.pop());
System.out.println(obj.peek());
System.out.println(obj.empty());
obj.empty();
}
}