找中点,后半段逆转,然后一前一后依次连接
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode tail = head;
head = head.next;
tail.next = null;
while (head != null) {
ListNode temp = head.next;
head.next = tail;
tail = head;
head = temp;
}
return tail;
}
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return;
//找中点,链表分成两个
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 翻转
ListNode newHead = slow.next;
slow.next = null;
newHead = reverseList(newHead);
// 依次连接
while (newHead != null) {
ListNode temp = newHead.next;
newHead.next = head.next;
head.next = newHead;
head = newHead.next;
newHead = temp;
}
}
}