Reorder List
2015-08-10 22:22
155 查看
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}.
实现最终的链表需要三步:将链表分成前后两段,反转后半部分,合并两个链表。
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}.
实现最终的链表需要三步:将链表分成前后两段,反转后半部分,合并两个链表。
public void reorderList(ListNode head) { if(head==null&&head.next!=null) return; ListNode fast=head,slow=head; while(fast!=null&&fast.next!=null&&fast.next.next!=null){ fast=fast.next.next; slow=slow.next; } ListNode t1=slow.next; slow.next=null; ListNode t2=reverseList(t1); ListNode t=head; while(t2!=null){ ListNode t3=t.next,t4=t2.next; t.next=t2; t2.next=t3; t=t3; t2=t4; } } public ListNode reverseList(ListNode head){ ListNode newHead=null; while(head!=null){ ListNode t=head.next; head.next=newHead; newHead=head; head=t; } return newHead; }
相关文章推荐
- 判断一年中某一天是这一年的第几天的函数接口
- 用UIImageView自带方法实现简单动画
- python numpy argsort函数用法
- QTableWidget 详细使用
- 集合,ArrayList
- 手机站与主站的SEO优化
- Java中接口和抽象类有哪些区别
- sonarQube代码质量管理
- Html5(2)新增的结构元素 及 新增页面元素
- 继承的构造和析构顺序
- 详解linux vi命令用法
- Caffe学习:Solver
- hdu 2665 划分树
- ec:table 的使用
- 二叉树的遍历(递归)
- java工具类Date 日期类应用
- 使用libcurl的正确姿势
- Ant配置
- 一些面试题目的总结
- 黑马程序员 oc随机 分类与延展