zoukankan      html  css  js  c++  java
  • 143. Reorder List

    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}.

    ===============

    思路:

    按照slow/fast方法找到链表的中间结点mid,

    此时中间节点将链表分为head1和head2,

    将head2链表按照revOnPlace(ListNode *head)就地逆置,

    遍历head1和head2两个链表,依次将head2链表中节点插入倒head1当中.

    此题就是麻烦,需要辅助函数showList(ListNode *head)调试.

    code如下:

    /**
     * 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;
            ListNode *slow, *fast;
            ListNode *prev;
            slow = fast = head;
            prev = nullptr;
            while(fast && fast->next)
            {
                prev = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            ListNode *head2 = prev->next;
            prev->next = nullptr;
    
            head2 = revOnPlace(head2);
            //cout<<"head1: ";showList(head);
            //cout<<"head2: ";showList(head2);
    
            ListNode *head1 = head;
            slow = head1;
            fast = head2;
            while(slow && fast){
                ListNode *t1 = slow->next;
                ListNode *t2 = fast->next;
                head1->next = slow;
                head1->next->next = fast;
                head1 = fast;
                slow = t1;
                fast = t2;
            }
            //cout<<"done";showList(head);
        }
        
        ListNode* revOnPlace(ListNode *head)
        {
            ListNode dummy(-1);
            ListNode *curr = head;
    
            head = &dummy;
            while(curr)
            {
                ListNode *tmp = curr->next;
                curr->next = head->next;
                head->next = curr;
                curr = tmp;
            }
    
            return dummy.next;
        }
    };
  • 相关阅读:
    Python3学习笔记22-文件读写
    Python3学习笔记21-实例属性和类属性
    Python3学习笔记20-获取对象信息
    Python3学习笔记19-继承和多态
    Python3学习笔记18-访问限制
    Python3学习笔记17-类与实例
    Python3学习笔记16-错误和异常
    Python3学习笔记15-迭代器与生成器
    Python3学习笔记14-迭代与列表生成式
    Python3学习笔记13-函数的参数
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5606933.html
Copyright © 2011-2022 走看看