forked from Jasmine-21/Java-FOP
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlasthalfreverse.java
More file actions
35 lines (33 loc) · 1 KB
/
lasthalfreverse.java
File metadata and controls
35 lines (33 loc) · 1 KB
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
import java.util.*;
public class lasthalfreverse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<Integer> stack = new Stack<>();
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while (n-- > 0)
stack.push(s.nextInt());
reverseSecondHalf(stack);
System.out.println(stack);
}
static void reverseSecondHalf(Stack<Integer> stack) {
int n = stack.size();
reverse(stack, n / 2);
}
static void reverse(Stack<Integer> stack, int n) {
if (n > 0) {
int temp = stack.pop();
reverse(stack, n - 1);
insertAtBottom(stack, temp, n - 1);
}
}
static void insertAtBottom(Stack<Integer> stack, int temp, int n) {
if (n == 0)
stack.push(temp);
else {
int temp2 = stack.pop();
insertAtBottom(stack, temp, n - 1);
stack.push(temp2);
}
}
}