题解
这个题是2019年408原题,就是我考研那年的题目,想想一年过去了,还是有点感慨的,希望明年这个时候的自己比现在更厉害吧
三个步骤:
(1)找到中间结点
(2)反转右半部分,记得将左半部分最后一个的next指针指向null(不要留野指针
(3)根据题目要求左边取一个,右边取一个
代码:
public class Solution143 {
public ListNode reverse(ListNode head){
ListNode temp = head;
ListNode temp1 = null;
ListNode temp2;
while (temp != null) {
temp2 = temp.next;
temp.next = temp1;
temp1 = temp;
temp = temp2;
}
return temp1;
}
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null){
return;
}
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode right = slow.next;
slow.next = null;
ListNode rightReverse = reverse(right);
ListNode dummy = new ListNode(-1);
ListNode temp = dummy;
ListNode leftTemp = head;
ListNode rightTemp = rightReverse;
while (leftTemp != null && rightTemp != null){
temp.next = leftTemp;
leftTemp = leftTemp.next;
temp = temp.next;
temp.next = rightTemp;
rightTemp = rightTemp.next;
temp = temp.next;
}
temp.next = leftTemp;
}
}