-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Stack.txt
88 lines (67 loc) · 2.32 KB
/
Reverse Stack.txt
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
Reverse Stack
Send Feedback
You have been given two stacks that can store integers as the data. Out of the two given stacks, one is populated and the other one is empty. You are required to write a function that reverses the populated stack using the one which is empty.
For Example:
Alt txt
Input Format :
The first line of input contains an integer N, denoting the total number of elements in the stack.
The second line of input contains N integers separated by a single space, representing the order in which the elements are pushed into the stack.
Output Format:
The only line of output prints the order in which the stack elements are popped, all of them separated by a single space.
Note:
You are not required to print the expected output explicitly, it has already been taken care of. Just make the changes in the input stack itself.
Constraints:
1 <= N <= 10^3
-2^31 <= data <= 2^31 - 1
Time Limit: 1sec
Sample Input 1:
6
1 2 3 4 5 10
Note:
Here, 10 is at the top of the stack.
Sample Output 1:
1 2 3 4 5 10
Note:
Here, 1 is at the top of the stack.
Sample Input 2:
5
2 8 15 1 10
Sample Output 2:
2 8 15 1 10
///////////////////////////---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.util.*;
public class Solution {
public static void reverseStack(Stack<Integer> input, Stack<Integer> extra) {
//Your code goes here
if (input.size()==0 || input.size()==1)
return;
Stack<Integer> temp = new Stack<>();
int n = input.size();
for(int i = 0;i < n; i++) {
extra.push(input.pop());
}
for(int i = 0;i < n; i++) {
temp.push(extra.pop());
}
for(int i = 0;i < n; i++) {
input.push(temp.pop());
}
}
}
///////////////---------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-----------------------------------------------------------------
import java.util.*;
public class Solution {
public static void reverseStack(Stack<Integer> input, Stack<Integer> extra) {
//Your code goes here
if (input.size()==0 || input.size()==1)
return;
int top=input.pop();
reverseStack(input, extra);
while(!input.isEmpty())
extra.push(input.pop());
input.push(top);
while(!extra.isEmpty())
input.push(extra.pop());
}
}