[leetcode] Reorder List

来源:互联网 发布:联网监控软件 编辑:程序博客网 时间:2024/06/08 10:09

Given a singly linked list L: L0L1→…→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}.

思路:先是将整个链表分割成两部分,将后半部分反转,然后与前半部分合并

输入格式:

4

1 2 3 4

代码如下:

#include<iostream>using namespace std;struct ListNode{        int val;        ListNode *next;        ListNode(int x):val(x),next(NULL){}};void reorderList(ListNode *head){        if(head==NULL) return;        if(head->next==NULL) return;        ListNode *slow=head,*fast=head;        while(fast->next!=NULL && fast->next->next!=NULL){                slow=slow->next;                fast=fast->next->next;        }           fast=slow->next;        slow->next=NULL;        ListNode *first,*second;        first=fast;        second=fast->next;        first->next=NULL;        ListNode *temp;        while(second!=NULL){                temp=second->next;                second->next=first;                first=second;                second=temp;        }           ListNode *lhalf;        lhalf=first;        ListNode *p=head;        ListNode *q=head;        int i=1;        q=q->next;        while(q!=NULL && lhalf!=NULL){                if(i%2==0){                        p->next=q;                        q=q->next;                }                   if(i%2!=0){                        p->next=lhalf;                        lhalf=lhalf->next;                }                   p=p->next;                i++;        }           if(q!=NULL) p->next=q;        else if(lhalf!=NULL) p->next=lhalf;}int main(){        int n,a;        cin>>n;        ListNode *head,*q;        head=(ListNode *)malloc(sizeof(ListNode));        q=head;        for(int i=0;i<n;i++){                cin>>a;                ListNode *p;                 p=(ListNode *)malloc(sizeof(ListNode));                p->val=a;                q->next=p;                q=p;        }        q->next=NULL;        ListNode *first=head->next;        reorderList(first);        while(first!=NULL){                cout<<first->val<<" ";                first=first->next;        }        cout<<endl;        return 0;}


0 0