zoukankan      html  css  js  c++  java
  • Reorder List leetcode

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You must do this in-place without altering the nodes' values.

    For example,
    Given {1,2,3,4}, reorder it to {1,4,2,3}.

    链表操作的思路往往比较容易想,但是实现起来就非常复杂。

    这里思路就是

    1.将链表分为前后两部分

    2.将后部分链表反转,这里反转我使用了一种新的方法(制造一个新的链表,将旧链表的结点依次添加到新链表的前端)

    3.构造新的链表,前后两部分链表结点交替添加到新链表中

    4.构造完成

    void reorderList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return;
        // 分割前后两部分
        ListNode *slow = head;
        ListNode *fast = head;
        while (fast->next != nullptr && fast->next->next != nullptr)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *head1 = head;
        ListNode *head2 = slow->next;
        slow->next = nullptr;
        head = head1;
        // 逆置链表
        ListNode *tail2 = head2;
        head2 = head2->next;
        tail2->next = nullptr;
        while (head2 != nullptr)
        {
            ListNode *temp = head2->next;
            head2->next = tail2;
            tail2 = head2;
            head2 = temp;        
        }
        // 交替构造新链表
        head2 = tail2;
        while (head2 != nullptr)
        {
            ListNode *temp = head1->next;
            head1->next = head2;
            head1 = temp;
            ListNode *temp2 = head2->next;
            head2->next = head1;
            head2 = temp2;
        }
    }
  • 相关阅读:
    HDU 1058 Humble Numbers
    HDU 1421 搬寝室
    HDU 1176 免费馅饼
    七种排序算法的实现和总结
    算法纲要
    UVa401 回文词
    UVa 10361 Automatic Poetry
    UVa 537 Artificial Intelligence?
    UVa 409 Excuses, Excuses!
    UVa 10878 Decode the tape
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5075381.html
Copyright © 2011-2022 走看看