https://leetcode.com/problems/reorder-list/
解题思路:
首先题目要求了要 in-place。表明我们不能创建一个新的链表,而只能通过改变指针的指向来重新排序。
一共分为三个步骤解决:
- 使用 slow 和 fast 指针找到链表中点,将链表分为两半。
- 将后半段链表反转。
- 最后将两段链表归并即可。
示意图:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head1 = head;
ListNode head2 = slow.next;
slow.next = null;
head2 = reverse(head2);
head = merge(head1, head2);
}
public ListNode reverse (ListNode head) {
ListNode prev = head;
ListNode curr = head.next;
head.next = null;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public ListNode merge (ListNode l1, ListNode l2) {
while (l2 != null) {
ListNode t1 = l1.next;
ListNode t2 = l2.next;
l1.next = l2;
l2.next = t1;
l1 = t1;
l2 = t2;
}
return l1;
}
}