-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathStack_using_Queue.java
97 lines (76 loc) · 1.9 KB
/
Stack_using_Queue.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
/* Java Program to implement a stack using two queue */
import java.util.*;
class Stack_using_Queue {
static class Stack {
// Two inbuilt queues
static Queue<Integer> q1 = new LinkedList<Integer>();
static Queue<Integer> q2 = new LinkedList<Integer>();
// To maintain current number of elements
static int size;
Stack()
{
size = 0;
}
static void push(int x)
{
size++;
// Push x first in empty q2
q2.add(x);
// Push all the remaining
// elements in q1 to q2.
while (!q1.isEmpty()) {
q2.add(q1.peek());
q1.remove();
}
// swap the names of two queues
Queue<Integer> q = q1;
q1 = q2;
q2 = q;
}
static void pop()
{
// if no elements are there in q1
if (q1.isEmpty())
return;
q1.remove();
size--;
}
static int top()
{
if (q1.isEmpty())
return -1;
return q1.peek();
}
static int size()
{
return size;
}
}
// driver code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Stack s = new Stack();
System.out.println("Enter the limit");
int n = sc.nextInt();
//accepting input from user
for(int i = 1; i <= n; i++)
s.push(i);
//printing the output
for(int i = 1; i <= n; i++){
System.out.println(s.top());
s.pop();
}
}
}
/* Time Complexity : O(n)
Space Complexity : O(n)
Input
5
Output
5
4
3
2
1
*/