• 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);
    }
  • 相关阅读:
    Linux源码Kconfig文件语法分析
    从0移植uboot (一) _配置分析
    ARM汇编与C混合编程
    ARM汇编程序结构
    ARMGNU伪指令
    Linux tcp黏包解决方案
    Linux 服务器模型小结
    Linux IPC udp/tcp/UNIX域 socket编程
    Linux IPC socket 广播,组播
    Linux I/O多路复用
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3795242.html
Copyright © 2020-2023  润新知