-
Notifications
You must be signed in to change notification settings - Fork 0
/
B分段翻转链表.java
61 lines (53 loc) · 1.6 KB
/
B分段翻转链表.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
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static class Node {
int val;
Node next = null;
Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int n = in.nextInt();
str = str.substring(1, str.length() - 1);
String[] val = str.split(",");
Node head = null;
for (int i = val.length - 1; i >= 0; i--) {
head = new Node(Integer.valueOf(val[i]), head);
}
Node temp = head;
int firstflag = 0;
Node preend = null;
ArrayList<Node> arr = new ArrayList<>(n);
while (temp != null) {
arr.add(temp);
if (arr.size() == n) {
temp = arr.get(n-1).next;
arr.get(0).next = temp;
if (firstflag == 0)
head = arr.get(n-1);
if (firstflag != 0)
preend.next = arr.get(n-1);
firstflag = 1;
preend = arr.get(0);
for (int i = n-1; i > 0; i--) {
arr.get(i).next = arr.get(i-1);
}
arr.clear();
continue;
}
if (temp.next == null)
break;
temp=temp.next;
}
while (head.next != null) {
System.out.println(head.val);
head = head.next;
}
System.out.println(head.val);
}
}