题目

Given a singly linked list L: 0143. Reorder List (M) - 图1,
reorder it to: 0143. Reorder List (M) - 图2

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example 1:

  1. Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

  1. Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

题意

将给定链表按照指定顺序重新排列为新链表。

思路

利用快慢指针找到中间结点,将链表分为左右两部分,将右链表逆序后逐个插入左链表的间隔中。


代码实现

Java

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public void reorderList(ListNode head) {
  11. if (head == null) {
  12. return;
  13. }
  14. // 找到中间结点
  15. ListNode slow = head, fast = head;
  16. while (fast.next != null && fast.next.next != null) {
  17. slow = slow.next;
  18. fast = fast.next.next;
  19. }
  20. ListNode rHead = null;
  21. ListNode p = slow.next;
  22. slow.next = null; // 注意断开左右链表,不然可能生成环
  23. // 逆置右链表
  24. while (p != null) {
  25. ListNode temp = p.next;
  26. p.next = rHead;
  27. rHead = p;
  28. p = temp;
  29. }
  30. // 将逆置后的右链表逐个插入左链表
  31. while (rHead != null) {
  32. ListNode temp = rHead.next;
  33. rHead.next = head.next;
  34. head.next = rHead;
  35. rHead = temp;
  36. head = head.next.next;
  37. }
  38. }
  39. }

JavaScript

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {void} Do not return anything, modify head in-place instead.
  11. */
  12. var reorderList = function (head) {
  13. if (!head) return
  14. let slow = head
  15. let fast = head
  16. while (fast.next && fast.next.next) {
  17. fast = fast.next.next
  18. slow = slow.next
  19. }
  20. let head2 = null
  21. let cur = slow.next
  22. slow.next = null
  23. while (cur) {
  24. let tmp = cur.next
  25. cur.next = head2
  26. head2 = cur
  27. cur = tmp
  28. }
  29. while (head2) {
  30. let tmp = head2.next
  31. head2.next = head.next
  32. head.next = head2
  33. head = head2.next
  34. head2 = tmp
  35. }
  36. }