-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution_143.java
More file actions
112 lines (102 loc) · 3.05 KB
/
Solution_143.java
File metadata and controls
112 lines (102 loc) · 3.05 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
143. 重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
*/
/*
1、快慢指针找中点
2、翻转后半段链表
3、插入
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
ListNode[] nodes = new ListNode[]{
new ListNode(1),new ListNode(2),new ListNode(3),new ListNode(4),new ListNode(5) };
nodes[0].next = nodes[1];
nodes[1].next = nodes[2];
nodes[2].next = nodes[3];
nodes[3].next = nodes[4];
ListNode t = nodes[0];
while ( t != null ) {
System.out.print(t+"+"+t.val+", ");
t = t.next;
}
System.out.println();
solution.reorderList(nodes[0]);
t = nodes[0];
while ( t != null ) {
System.out.print(t+"+"+t.val+", ");
t = t.next;
}
}
public void reorderList(ListNode head) {
if ( head == null || head.next == null || head.next.next == null)
return;
ListNode mid = getMiddle(head);
mid = reverseList(mid);
System.out.print("翻转后:");
ListNode t = mid;
while ( t != null ) {
System.out.print(t+"+"+t.val+", ");
t = t.next;
}
System.out.println();
intersectList(head, mid);
}
public ListNode getMiddle(ListNode head) {
ListNode fast = head;
ListNode low = head;
ListNode pre = new ListNode(0);
while ( fast != null && fast.next != null ) {
fast = fast.next.next;
pre = low;
low = low.next;
}
if ( fast != null ) {
ListNode t = low.next;
low.next = null;
return t;
} else {
pre.next = null;
return low;
}
}
public ListNode reverseList(ListNode head) {
if ( head == null || head.next == null )
return head;
ListNode h = new ListNode(0);
h.next = head;
ListNode cur = head.next;
head.next = null;
while ( cur != null ) {
ListNode t = cur.next;
cur.next = h.next;
h.next = cur;
cur = t;
}
return h.next;
}
public void intersectList(ListNode head, ListNode mid) {
ListNode f = head, s = mid;
while ( f != null && s != null ) {
ListNode m = head;
while ( m != null ) {
System.out.print(m+"+"+m.val+", ");
m = m.next;
}
System.out.println();
System.out.println(f.val+" "+s.val);
ListNode t = s.next;
s.next = f.next;
f.next = s;
f = f.next.next;
s = t;
}
}
}