您的位置:首页 > 其它

《leetCode》:Reorder List

2016-03-03 11:12 676 查看

题目

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


思路一:报超时错误

利用两个循环来做,即每次将链表中最后一个节点找到并插入到相应的位置。

时间复杂度为:O(n^2)

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
void reorderList(struct ListNode* head) {
if(head==NULL||head->next==NULL){
return;
}
//用两个for循环来做
struct ListNode* cur=head;
struct ListNode* next=NULL;
struct ListNode* final=NULL;
struct ListNode* preFinal=NULL;
while(cur->next!=NULL&&cur->next->next!=NULL){
next=cur->next;//保存下一个节点
//使得node指向最后一个节点的位置
final=cur;
preFinal=NULL;
while(final->next!=NULL){
preFinal=final;
final=final->next;
}
preFinal->next=NULL;
cur->next=final;
final->next=next;
cur=next;
}
}


思路二

先找到即将要插入的后面一半的链表的起始点,然后将其翻转作为一个新链表,最后合并即为所求

实现代码如下:

//合并两个链表
void combineList(struct ListNode* head,struct ListNode* newHead){
if(head==NULL){
head=newHead;
return ;
}
if(newHead==NULL){
return;
}
struct ListNode* cur1=head;
struct ListNode* next1=NULL;
struct ListNode* cur2=newHead;
struct ListNode* next2=NULL;
while(cur1!=NULL&&cur2!=NULL){
next1=cur1->next;
next2=cur2->next;
cur1->next=cur2;
if(next1!=NULL){
cur2->next=next1;
}
cur1=next1;
cur2=next2;
}
}
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL){
return NULL;
}
struct ListNode* pre=NULL;
struct ListNode* cur=head;
struct ListNode* next=NULL;
while(cur->next!=NULL){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
cur->next=pre;//把最后一个节点连接上
return cur;
}
/*
思路:先找到即将要插入的后面一半的链表的起始点,然后将其翻转,最后合并即为所有
*/
void reorderList(struct ListNode* head) {
if(head==NULL||head->next==NULL){
return;
}
struct ListNode* slow=head;
struct ListNode* fast=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
//翻转slow后面的节点成为一个新的链表
struct ListNode* node=reverseList(slow->next);
slow->next=NULL;
//合并
combineList(head,node);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: