forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackUsingQueue.java
98 lines (82 loc) · 2 KB
/
StackUsingQueue.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Java Program to implement a stack using two queues
by making the push operation costly*/
import java.util.*;
public class StackUsingQueue {
static class Stack {
// the 2 queues
Queue<Integer> qu1 = new LinkedList<>();
Queue<Integer> qu2 = new LinkedList<>();
// storing current size
int currentSize;
Stack() {
currentSize = 0;
}
void push(int num) {
currentSize++;
// first, push num into an empty qu2
qu2.add(num);
// now we push the other elements from qu1 to qu2
while (!qu1.isEmpty()) {
qu2.add(qu1.peek());
qu1.remove();
}
}
void pop() {
if (qu2.isEmpty()) {
return;
}
// remove element and reduce size if qu2 not empty
qu2.remove();
currentSize--;
}
int top() {
if (qu2.isEmpty()) {
return -1;
}
// return the top element
return qu2.peek();
}
int size() {
return currentSize;
}
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner sc = new Scanner(System.in);
System.out.println("Enter size:");
int size = sc.nextInt();
System.out.println("Enter the numbers:");
for (int i = 0; i < size; i++) {
stack.push(sc.nextInt());
}
sc.close();
System.out.println("Current Size:" + stack.size());
for (int i = size; i > 0; i--) {
System.out.println(stack.top());
stack.pop();
}
System.out.println("Current Size:" + stack.size());
}
}
/**
* Sample input/output:
*
* Enter size:
* 5
* Enter the numbers:
* 5
* 4
* 3
* 2
* 1
* Current Size:5
* 5
* 4
* 3
* 2
* 1
* Current Size:0
*
* Time complexity: O(n) for push, O(1) for pop
* Space complexity: O(n)
*/