《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); }
相关文章推荐
- Fatal: the Postfix mail system is already running 的解决方案
- 种一颗树最好的时间是十年前,而后是现在
- 查看oracle数据库的连接数以及用户
- android studio 签名 报错Error:(3) Error: "app_name" is not translated in "de" (German), "es" (Spanish),
- 总结
- Activithy切换动画
- Hadoop集群(第4期)_SecureCRT使用
- (转)进程同步之临界区域问题及Peterson算法
- 入侵分析十诫
- apache实现多域名虚拟主机的SSL认证
- spark mllib 频繁项 FPGrowth
- CocoaPods安装
- Exporting a function in a DLL using Microsoft Visual C++ 6.0
- 【Unity开发】通过C#读取CSV表,创建并存储到LUA table中
- 五大常用算法之一:分治算法
- [.Net码农]Newtonsoft.Json 用法
- [.Net码农]用Json.NET将json字符串反序列化为json匿名对象
- Hadoop集群(第3期)_VSFTP安装配置
- json字符串转成对象
- 获取屏幕高度,兼容性问题解决