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

    解题思路:

    分三步:

      1.找到中点并且将链表断成两个链表

      2.将第二个链表翻转

      3.将第一个链表和第二个链表穿插起来

    需要注意的是:

      当链表节点为奇数个时,此时l2(也就是后半部分链表)会剩余一个,可能会被丢掉

      所以添加高亮处来防止被丢掉

    代码:

    /**
     * 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 || !head->next || !head->next->next)
                return;
            //find the middle point
            ListNode* fast = head;
            ListNode* slow = head;
            ListNode* pre = head;
            while(fast && fast->next){
                pre = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            pre->next = NULL;
            //reverse the second part
            pre = slow;
            slow = slow->next;
            pre->next = NULL;
            while(slow){
                ListNode* temp = slow->next;
                slow->next = pre;
                pre = slow;
                slow =temp;
            }
            ListNode *l1 = head, *l2 = pre;
            while(l1 && l2){
                ListNode* temp1 = l1->next;
                ListNode* temp2 = l2->next;
                l1->next = l2;
                if(temp1)
                    l2->next = temp1;
                l1 = temp1;
                l2 = temp2;
            }
            
        }
    };
  • 相关阅读:
    游标
    mobaxterm安装与使用(root_35/37/36/121)
    美团笔试--修改矩阵
    美团笔试1--螺旋矩阵
    assert函数
    2019年头条笔试--围坐分糖果
    邻值查找——stl函数lower_bound和upper_bound的使用
    动态规划练习1--腾讯暑期实习正式批
    Windows 7下硬盘安装CentOS6.4的解决方法
    Sublime Text 3 的一些基本使用方法和配置
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9172540.html
Copyright © 2011-2022 走看看