- Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathQueueUsingStack.java
More file actions
Latest commit
47 lines (41 loc) · 1.33 KB
/
Copy pathQueueUsingStack.java
File metadata and controls
47 lines (41 loc) · 1.33 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
packagestackqueues.queueusingstack;
importjava.util.Stack;
/**
* Implement a queue using stack. The idea is to use two stacks.
* Push everything on stack1.
* Pop everything from stack1 into push on stack2 if stack2 is not empty.
* Queue A B C
* C -> A -> A B C
* B pop1 B pop
* A push2 C
* Stack 1 Stack 2
* User: rpanjrath
* Date: 9/19/13
* Time: 1:56 PM
*/
publicclassQueueUsingStack {
privateStack<String> stack1 = newStack<>();
privateStack<String> stack2 = newStack<>();
publicvoidadd(Stringtemp) {
stack1.push(temp);
}
publicStringremove() {
if (stack2.isEmpty()) { // V Imp else we can concurrently modify the stacks
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
returnstack2.pop();
}
publicstaticvoidmain(String[] args) {
QueueUsingStackqueueUsingStack = newQueueUsingStack();
queueUsingStack.add("A");
queueUsingStack.add("B");
queueUsingStack.add("C");
System.out.print(queueUsingStack.remove());
System.out.print(queueUsingStack.remove());
queueUsingStack.add("D");
System.out.print(queueUsingStack.remove());
System.out.print(queueUsingStack.remove());
}
}