zoukankan      html  css  js  c++  java
  • Leetcode ReorderList

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

    (1)找出中间节点

    (2)将后部分节点反转

    (3)将前部分节点和后部分节点合并

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <unordered_map>
    #include <list>
    
    using namespace std;
    
    struct ListNode{
        int val;
        ListNode *next;
        ListNode(int x):val(x), next(NULL){}
    };
    
    void printList(ListNode* head){
        while(head!=NULL){
            cout<<"->"<<head->val;
            head = head->next;
        }
        cout<<endl;
    }
    
    ListNode* reverse(ListNode *head){
        ListNode *pre = head;
        ListNode *p = head->next;
        head->next =NULL;
        while(p!=NULL){
            ListNode* tmp = p->next;
            p->next = pre;
            pre = p;
            p = tmp;
        }
        return pre;
    }
    
    ListNode* merge(ListNode *head1, ListNode *head2){
        ListNode* p = head1;
        while(head2!=NULL){
            ListNode *tmp = head2->next;
            head2->next = p->next;
            p->next = head2;
            p = p->next->next;
            head2 = tmp;
        }
        return head1;
        
    }
    
    void reorderList(ListNode *head){
        if(head == NULL || head->next == NULL) return;
        ListNode *slow = head,*fast = head;
        while(fast->next && fast->next->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *head2 = slow->next;
        slow->next = NULL;
        ListNode *head1 = head;
        //printList(head2);
        head2 = reverse(head2);
        //printList(head2);
        head =  merge(head1,head2);
    }
    
    int main(){
        ListNode *head= new ListNode(1);
        ListNode *p = head;
        for(int i =2; i <= 7; ++ i){
            ListNode *a= new ListNode(i);
            p->next = a;
            p = a;
        }
        reorderList(head);
        printList(head);
    }
  • 相关阅读:
    读《猫城记》 | 人间失格
    如果这都算是佛系
    常规流(Normal flow)
    页面重绘(repaint)和回流(reflow)
    display:none和visiblity:hidden区别
    读《人类简史》 | 一本很值得读的书
    Mac shell笔记
    读《围城》
    珠海游记
    mouseout、mouseover和mouseleave、mouseenter区别
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3795242.html
Copyright © 2011-2022 走看看