• 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;
        }
    };




  • 相关阅读:
    C语言编程的两个工具:valgrind和core
    C语言动态库和静态库的使用及实践
    编译安装pgbouncer-checking for OpenSSL... configure: error: not found
    automake使用
    make笔记
    GCC命令
    gcc中关于静态库和动态库使用(转)
    zookeeper的c API 单线程与多线程问题 cli_st和cli_mt
    zookeeper数据一致性与paxos算法
    Deepgreen DB简介(转)
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/7314ea85c8387fd6825d2526f3d74aa3.html
Copyright © 2020-2023  润新知