[LeetCode][143] Reorder List

先遍历一遍知道有多长 然后取到中间把整个链表断开

然后把后半部分反转 并且一一merget到前部份


/*
 * @lc app=leetcode id=143 lang=cpp
 *
 * [143] Reorder List
 *
 * https://leetcode.com/problems/reorder-list/description/
 *
 * algorithms
 * Medium (29.57%)
 * Total Accepted:    142K
 * Total Submissions: 478.1K
 * Testcase Example:  '[1,2,3,4]'
 *
 * Given a singly linked list L: L0→L1→…→Ln-1→Ln,
 * reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
 *
 * You may not modify the values in the list's nodes, only nodes itself may be
 * changed.
 *
 * Example 1:
 *
 *
 * Given 1->2->3->4, reorder it to 1->4->2->3.
 *
 * Example 2:
 *
 *          *
 * Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
 *
 *
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
 public:
  void reorderList(ListNode* head) {
    if (head == nullptr || head->next == nullptr) {
      return;
    }
    int len = 1;
    ListNode* temp = head;
    while (temp->next != nullptr) {
      temp = temp->next;
      len++;
    }
    //反转后半部分的链表然后加入到前半部分
    temp = head;
    int cnt = 1;

    while (cnt != len / 2) {
      temp = temp->next;
      cnt++;
    }

    ListNode* H = new ListNode(0);
    H->next = temp->next;
    temp->next = nullptr;

   // show2(head, H->next);

    reverse(H);

    merget(head, H->next);
    //show2(head, H->next);
    // show(H->next);

    return;
  }
  void show2(ListNode* h1, ListNode* h2) {
    show(h1);
    cout << "\n";
    show(h2);
  }
  void merget(ListNode* h1, ListNode* h2) {
    while (h1->next != nullptr && h2->next != nullptr) {
      ListNode *t1 = h1->next, *t2 = h2->next;
      h1->next = h2;
      h2->next = t1;
      h2 = t2;
      h1 = t1;
    }
    if (h1->next == nullptr) {
      h1->next = h2;
    }
  }
  void reverse(ListNode* H) {
    //空的头节点和只有一个节点的情况
    if (H->next == nullptr || H->next->next == nullptr) {
      return;
    }
    ListNode *fast = H->next->next, *slow = H->next;

    ListNode* t = fast;
    while (fast != nullptr) {
      t = t->next;
      fast->next = slow;
      slow = fast;
      fast = t;
    }
    H->next->next = nullptr;
    H->next = slow;
  }
  void show(ListNode* t) {
    while (t != nullptr) {
      cout << t->val << " ";
      t = t->next;
    }
    cout << endl;
  }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值