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

    • Total Accepted: 84681
    • Total Submissions: 341465
    • Difficulty: Medium
    • Contributors: Admin

    Given a singly linked list LL0L1→…→Ln-1Ln,
    reorder it to: L0LnL1Ln-1L2Ln-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
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
      
     /** 
      * slow fast pointer
      * [1,2,3,4] 2
      * [1,2,3,4,5] 3
      * [1,2,3,4,5,6] 3
      * ...
      */
    class Solution {
    public:
        void reorderList(ListNode* head) {
            if(head == NULL || head->next == NULL) return;
             
            ListNode* slow = head, * fast = head;
            while(fast && fast->next && fast->next->next){
                slow = slow->next;
                fast = fast->next->next;
            }
             
            ListNode* l1 = head;
            ListNode* l2 = reverse(slow->next);
            slow->next = NULL;
             
            ListNode dummy(0);
            ListNode* p = &dummy;
            bool sign = false;
            while(l2){
                if(sign){
                    p->next = l2;
                    l2 = l2->next;
                }
                else{
                    p->next = l1;
                    l1 = l1->next;
                }
                p = p->next;
                sign = !sign;
            }
            p->next = l1;
             
        }
        ListNode* reverse(ListNode* head){
            if(head == NULL || head->next == NULL) return head;
            ListNode* p = NULL, * cur = head;
            while(cur){
                ListNode* tmp = cur->next;
                cur->next = p;
                p = cur;
                cur = tmp;
            }
            return p;
        }
    };




  • 相关阅读:
    IOS7 About
    iOS Newsstand Tutorial
    微信开发商
    网络流量监控相关资料
    EDM about
    thinkphp验证码的实现
    thinkphp表单上传文件并将文件路径保存到数据库中
    thinkphp分页实现
    linux 系统简单备份
    Google Hacking总结
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/7314ea85c8387fd6825d2526f3d74aa3.html
Copyright © 2011-2022 走看看