Reorder List解题报告

Description:

Given a singly linked list L: L0?L1?…?Ln-1?Ln,
reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?…

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

Example:

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

Link:

https://leetcode.com/problems/reorder-list/description/

解题方法:

  1. 找到中点将List分为两部分
  2. 将后半部分逆置
  3. 将后半部分插入到前半部分

Tips:

在这里求中点的方法与其他题目有一点不同,我们需要保证在node(假设node编号从1~2n)的个数为偶数的情况下求到第n个,而不是第n+1个:

while(fast && fast->next && fast->next->next)
{
            fast = fast->next->next;
            slow = slow->next;
}

Time Complexity:

O(N)时间
O(0)空间

完整代码:

void reorderList(ListNode* head) 
{
        if(!head)
            return;
        //get the start node of second part
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next && fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* second = slow->next;
        slow->next = NULL;
        //reverse second part
        ListNode* prev = NULL;
        ListNode* curr = second;
        while(curr)
        {
            ListNode* next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        second = prev;
        //build new list
        ListNode* first = head;
        while(second)
        {
            ListNode* temp1 = first->next;
            ListNode* temp2 = second->next;
            first->next = second;
            second->next = temp1;
            first = temp1;
            second = temp2;
        }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容