forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Queue_using_Stack.java
85 lines (71 loc) · 1.53 KB
/
Queue_using_Stack.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
// Java program to implement Queue using two stacks with costly enQueue()
import java.util.*;
class QueuetoStack
{
static class Queue
{
static Stack<Integer> stk1 = new Stack<Integer>();
static Stack<Integer> stk2 = new Stack<Integer>();
static void enQueue(int x)
{
// Move all elements from stk1 to stk2
while (!stk1.isEmpty())
{
stk2.push(stk1.pop());
//stk1.pop();
}
// Push item into stk1
stk1.push(x);
// Push everything back to stk1
while (!stk2.isEmpty())
{
stk1.push(stk2.pop());
//stk2.pop();
}
}
// Dequeue an item from the queue
static int deQueue()
{
// if first stack is empty
if (stk1.isEmpty())
{
System.out.println("Q is Empty");
System.exit(0);
}
// Return top of stk1
int s = stk1.peek();
stk1.pop();
return s;
}
};
// Main method
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter limit");
int n = sc.nextInt();
Queue qu = new Queue();
for(int i = 1; i <= n; i++)
qu.enQueue(i);
for(int i = 1; i <= n; i++)
System.out.println(qu.deQueue());
}
}
/* Time Complexity:
1) Push operation: O(N).
2) Pop operation: O(1).
Space Complexity: O(N).
Input:
10
Output:
1
2
3
4
5
6
7
8
9
10
*/