Reorder List leetcode java
2024-10-20 11:42:55
题目:
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}
.
题解:
题目要重新按照 L0→Ln→L1→Ln-1→L2→Ln-2→…来排列,看例子1->2->3->4会变成1->4->2->3,拆开来看,是{1,2}和{4,3}的组合,而{4,3}是{3,4}的逆序。这样问题的解法就出来了。
第一步,将链表分为两部分。
第二步,将第二部分链表逆序。
第三步,将链表重新组合。
代码如下:
1 public void reorderList(ListNode head) {
2 if(head==null||head.next==null)
3 return;
4
5 ListNode slow=head, fast=head;
6 ListNode firsthalf = head;
7 while(fast.next!=null&&fast.next.next!=null){
8 slow = slow.next;
9 fast = fast.next.next;
}
ListNode secondhalf = slow.next;
slow.next = null;
secondhalf = reverseOrder(secondhalf);
while (secondhalf != null) {
ListNode temp1 = firsthalf.next;
ListNode temp2 = secondhalf.next;
firsthalf.next = secondhalf;
secondhalf.next = temp1;
firsthalf = temp1;
secondhalf = temp2;
}
}
public static ListNode reverseOrder(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode pre = head;
ListNode curr = head.next;
while (curr != null) {
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
// set head node's next
head.next = null;
return pre;
}
Reference://http://www.programcreek.com/2013/12/in-place-reorder-a-singly-linked-list-in-java/
最新文章
- VMware中linux配置1-安装VMware tool 共享文件夹
- PL/SQL 导出dmp文件时发现表少了
- Django跑起来
- 15SpringMvc_在业务控制方法中写入模型变量收集参数,且使用@InitBind来解决字符串转日期类型
- 关于异常的疑难解答:System.Runtime.InteropServices.COMException
- 10_RHEL安装搜狗输入法
- 异步消息处理机制——Handler用法
- Linux下安装Wireshark
- graph driver-device mapper-04libdevmapper基本操作
- JQuery EasyUI combobox(下拉列表框)
- 安卓笔记-- popupwindow back键不消失的问题
- Unity的资源管理
- Linux ACL 权限
- python3 列表list
- Hbase学习笔记——基本CRUD操作
- Redux和React-Redux的实现(二):Provider组件和connect的实现
- 在asp.net中执行存储过程(转)
- Unity下的ECS框架 Entitas简介
- 深入理解JavaScript系列(17):面向对象编程之概论
- 01_常用的MIME类型