您的位置:首页 > 其它

[leetcode] Reorder List

2014-07-07 14:36 381 查看
Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→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}.

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

输入格式:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode