Leetcode ReorderList

OpenSoucre發表於2014-06-18

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

 

相關文章