Skip to content

Commit efd0a5a

Browse files
committed
143.重排链表,递归
1 parent d5eb9e2 commit efd0a5a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

leetcode_Java/Solution0143.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,38 @@ private ListNode reverse(ListNode head) {
109109
}
110110
return before;
111111
}
112+
}
113+
114+
115+
/*
116+
递归
117+
*/
118+
class Solution {
119+
public void reorderList(ListNode head) {
120+
int count = 0;
121+
ListNode cur = head;
122+
while(cur != null){
123+
cur = cur.next;
124+
count++;
125+
}
126+
if(count <= 2) {
127+
return;
128+
}
129+
reorderList(head, count);
130+
}
131+
132+
private ListNode reorderList(ListNode head, int count){
133+
if(count == 1) {
134+
return head;
135+
} else if (count == 2) {
136+
return head.next;
137+
}
138+
ListNode midTail = reorderList(head.next, count - 2);
139+
ListNode headNext = head.next;
140+
ListNode after = midTail.next;
141+
midTail.next = after.next;
142+
head.next = after;
143+
after.next = headNext;
144+
return midTail;
145+
}
112146
}

0 commit comments

Comments
 (0)