题解 | #重排链表#

重排链表

https://www.nowcoder.com/practice/3d281dc0b3704347846a110bf561ef6b

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
  public:
    ListNode* reverse(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }
        auto newHead = reverse(head->next);
        head->next->next = head;
        head->next = nullptr;
        return newHead;
    }
    ListNode* merge(ListNode* h1, ListNode* h2) {
        ListNode* r = h1;
        int cnt = 1;
        while ((h1 != h2) && h1 && h2) {
            if (cnt & 1) {
                ListNode* next = h1->next;
                h1->next = h2;
                h1 = next;
            } else {
                ListNode* next = h2->next;
                h2->next = h1;
                h2 = next;
            }
            cnt++;
        }
        return r;
    }
    void reorderList(ListNode* head) {
        ListNode* fast = head;
        ListNode* low = head;
        while (fast != nullptr && fast->next != nullptr) {
            fast = fast->next->next;
            low = low->next;
        }
        ListNode* mid = low;
        mid = reverse(mid);
        merge(head, mid);


    }
};

我考虑的有点复杂了感觉

全部评论

相关推荐

06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务