Skip to content

Commit cc3bf63

Browse files
authored
Create Stack-Reverse Stack
1 parent eca15ef commit cc3bf63

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Stack-Reverse Stack

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
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.
2+
For Example:
3+
Alt txt
4+
5+
Input Format :
6+
The first line of input contains an integer N, denoting the total number of elements in the stack.
7+
8+
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.
9+
Output Format:
10+
The only line of output prints the order in which the stack elements are popped, all of them separated by a single space.
11+
Note:
12+
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.
13+
Constraints:
14+
1 <= N <= 10^3
15+
-2^31 <= data <= 2^31 - 1
16+
17+
Time Limit: 1sec
18+
Sample Input 1:
19+
6
20+
1 2 3 4 5 10
21+
Note:
22+
Here, 10 is at the top of the stack.
23+
Sample Output 1:
24+
1 2 3 4 5 10
25+
Note:
26+
Here, 1 is at the top of the stack.
27+
Sample Input 2:
28+
5
29+
2 8 15 1 10
30+
Sample Output 2:
31+
2 8 15 1 10
32+
33+
********************************Code**********************************
34+
35+
public static void reverseStack(Stack<Integer> input, Stack<Integer> extra) {
36+
37+
if (input.size()==0 || input.size()==1)
38+
{
39+
return;
40+
}
41+
int top=input.pop();
42+
reverseStack(input,extra);
43+
while(!input.isEmpty())
44+
{
45+
extra.push(input.pop());
46+
}
47+
input.push(top);
48+
49+
while(!extra.isEmpty())
50+
{
51+
input.push(extra.pop());
52+
}
53+
}

0 commit comments

Comments
 (0)