143. 重排链表
2020-05-17 本文已影响0人
最困惑的时候就是能成长的时候
1.想法
1.从题目的题意可知,我们需要三步,
step 1:将现有的链表分成两个部分1.L0→L中 2.L中+1→Ln(寻找链表的中间节点) 快慢指针
step 2:翻转后一部分的链表(翻转链表) 翻转链表
step 3:合并这两部分链表(链表合并)
2.代码
class Solution {
public void reorderList(ListNode head) {
//极端情况
if(head == null||head.next == null)return;
//1.找到中间节点
ListNode midHead = getMidNode(head);
ListNode midNext = midHead.next;
midHead.next = null;
//2.翻转后面的列表
ListNode midNextHead = reverseNode(midNext);
//3.结合两个链表
ListNode temp = head,l0 = head.next,l1 = midNextHead;
temp.next = l1;
l1= l1.next;
temp = temp.next;
while(l1!=null){
temp.next = l0;
l0 = l0.next;
temp = temp.next;
temp.next =l1;
l1 = l1.next;
temp = temp.next;
}
if(l0!=null){
temp.next = l0;
}
}
private ListNode reverseNode(ListNode midNext) {
ListNode pre = null,now = midNext,next = now.next;
while(next!=null){
now.next = pre;
pre = now;
now = next;
next = now.next;
}
now.next = pre;
return now;
}
private ListNode getMidNode(ListNode head) {
ListNode mid = head;
int count = 1;
while(head.next!=null){
head = head.next;
count++;
if(count%2!=0){
mid = mid.next;
}
}
return mid;
}
}