Reorder List
2016-05-23 20:38
267 查看
题目描述:
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}.
比如1,2,3,4,5,6,7,要得到的结果是1,7,2,6,3,5,4.
1、先把数组分成两个部分:1,2,3,4和5,6,7
2、将5,6,7逆序得到7,6,5
3、然后将7,6,5插入到1,2,3,4中
逆序,插入,查找链表中第k个数,这些都是很熟悉的操作,代码如下:
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}.
比如1,2,3,4,5,6,7,要得到的结果是1,7,2,6,3,5,4.
1、先把数组分成两个部分:1,2,3,4和5,6,7
2、将5,6,7逆序得到7,6,5
3、然后将7,6,5插入到1,2,3,4中
逆序,插入,查找链表中第k个数,这些都是很熟悉的操作,代码如下:
public void reorderList(ListNode head) { int sum=0; ListNode p=head; //得到链表的长度 while(p!=null){ p=p.next; sum++; } if(sum<=2) return; int n=(sum+1)/2; /*将链表分成两个链表。第一个链表head开头,n个,第二个链表head2开头,sum-n个,注意这里的第一个链表最后一个节点的next要赋值为null*/ p=head; while(n>1){ p=p.next; n--; } ListNode head2=p.next; p.next=null; //tail找到整个链表的最后一个节点 ListNode tail=head2; while(tail.next!=null){ tail=tail.next; } //将第二个数组逆序 p=tail; while(head2!=tail){ ListNode next=head2.next; head2.next=tail.next; tail.next=head2; head2=next; } head2=tail; p=head; //将第二个数组插入到第一个数组中 while(head2!=null){ ListNode next=head2.next; ListNode pnext=p.next; head2.next=p.next; p.next=head2; head2=next; p=pnext; } }
相关文章推荐
- STL之Set自定义排序
- Linux下0号进程的前世(init_task进程)今生(idle进程)----Linux进程的管理与调度(五)
- 拓扑排序
- hdoj2052Picture
- 【CF52C】Circular RMQ(线段树区间加减,区间最值)
- CentOS 7编译安装Nginx1.9.0
- Dos界面 五步棋
- zoj(1095)
- 关于c语言程序的感受
- DataInputString
- maven整合:最新ssm框架实现spring4.2,springmvc4.2,mybatis3.2
- zookeeper基本API的使用
- 第十一周项目1-分数类中的运算符重载(1)
- OC 习题:股票K线计算
- 添加远程库
- Codeforces Round #353 (Div. 2) E 线段树+dp
- POJ 2114 Boatherds 树的分治
- {题解}[jzoj3396] 【NOIP2013模拟】Rainbow的信号
- 【NOIP2013模拟】Rainbow的信号
- struts2运行出现The requested is not available(404)错误,解决方案