题目描述

给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

链接:https://leetcode-cn.com/problems/reorder-list

示例1
129 重排链表 - 图1

解题思路

为了减少空间复杂度,我们可以这样来做,由题目来看我们先把链表分成两半,然后对后一半进行逆序,最后再逐个插入到第一个链表即可:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* find_mid(ListNode* head) {
  14. // 确保链表至少有两个节点
  15. ListNode* fast = head;
  16. ListNode* slow = new ListNode(-1);
  17. slow->next = head;
  18. while (fast && fast->next) {
  19. slow = slow->next;
  20. fast = fast->next->next;
  21. }
  22. return slow;
  23. }
  24. ListNode* reverse_list(ListNode* head) {
  25. ListNode* pre_node = NULL;
  26. ListNode* curr = head;
  27. while (curr) {
  28. ListNode* temp = curr->next;
  29. curr->next = pre_node;
  30. pre_node = curr;
  31. curr = temp;
  32. }
  33. return pre_node;
  34. }
  35. void reorderList(ListNode* head) {
  36. ListNode* mid_node = find_mid(head);
  37. if (mid_node->val == -1)
  38. return;
  39. ListNode* half_front = head;
  40. ListNode* half_back = mid_node->next;
  41. mid_node->next = NULL;
  42. half_back = reverse_list(half_back);
  43. ListNode* curr = new ListNode();
  44. ListNode* ret = new ListNode();
  45. ret->next = curr;
  46. while (half_front || half_back) {
  47. if (half_front) {
  48. curr->next = half_front;
  49. half_front = half_front->next;
  50. curr = curr->next;
  51. }
  52. if (half_back) {
  53. curr->next = half_back;
  54. half_back = half_back->next;
  55. curr = curr->next;
  56. }
  57. }
  58. head = ret->next;
  59. }
  60. };