题意:

image.png

解题思路:

  1. 思路:
  2. 1.找到链表的中点
  3. 2.以中点分割链表为2部分
  4. 3.反转分割的右链表
  5. 4.将左右链表依次拼接

图示:
143. 重排链表.png

PHP代码实现:

  1. /*
  2. * @lc app=leetcode.cn id=143 lang=php
  3. *
  4. * [143] 重排链表
  5. *
  6. * https://leetcode-cn.com/problems/reorder-list/description/
  7. *
  8. * algorithms
  9. * Medium (52.13%)
  10. * Likes: 140
  11. * Dislikes: 0
  12. * Total Accepted: 14.1K
  13. * Total Submissions: 26.1K
  14. * Testcase Example: '[1,2,3,4]'
  15. *
  16. * 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
  17. * 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
  18. * 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
  19. *
  20. * 示例 1:
  21. * 给定链表 1->2->3->4, 重新排列为 1->4->2->3.
  22. * 示例 2:
  23. * 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
  24. */
  25. // @lc code=start
  26. /**
  27. * Definition for a singly-linked list.
  28. * class ListNode {
  29. * public $val = 0;
  30. * public $next = null;
  31. * function __construct($val) { $this->val = $val; }
  32. * }
  33. */
  34. class Solution {
  35. /**
  36. * @param ListNode $head
  37. * @return NULL
  38. */
  39. function reorderList($head) {
  40. $slow = $head;
  41. $fast = $head;
  42. while ($fast->next != null && $fast->next->next != null) {
  43. $slow = $slow->next;
  44. $fast = $fast->next->next;
  45. }
  46. $newHead = $slow->next;
  47. $slow->next = null;
  48. $newHead = $this->reverseList($newHead);
  49. while ($newHead != null) {
  50. $tmp = $newHead->next;
  51. $newHead->next = $head->next;
  52. $head->next = $newHead;
  53. $head = $newHead->next;
  54. $newHead = $tmp;
  55. }
  56. }
  57. function reverseList($head) {
  58. if ($head == null || $head->next == null) return $head;
  59. $p = $this->reverseList($head->next);
  60. $head->next->next = $head;
  61. $head->next = null;
  62. return $p;
  63. }
  64. }
  65. // @lc code=end

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func reorderList(head *ListNode) {
  9. if head == nil || head.Next == nil {
  10. return
  11. }
  12. fast, slow := head, head
  13. for fast != nil && fast.Next != nil {
  14. fast, slow = fast.Next.Next, slow.Next
  15. }
  16. newHead := slow.Next
  17. slow.Next = nil //分割两个链表
  18. newHead = reverse(newHead) // 反转中点以后的链表
  19. // 将两个链表拼接
  20. for newHead != nil {
  21. tmp := newHead.Next
  22. newHead.Next = head.Next
  23. head.Next = newHead
  24. head, newHead = newHead.Next, tmp
  25. }
  26. }
  27. func reverse(head *ListNode) *ListNode {
  28. if head == nil || head.Next == nil {
  29. return head
  30. }
  31. p := reverse(head.Next)
  32. head.Next.Next = head
  33. head.Next = nil
  34. return p
  35. }