题目

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

题解:

题目要重新按照 L0LnL1Ln-1L2Ln-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/

最新文章

  1. VMware中linux配置1-安装VMware tool 共享文件夹
  2. PL/SQL 导出dmp文件时发现表少了
  3. Django跑起来
  4. 15SpringMvc_在业务控制方法中写入模型变量收集参数,且使用@InitBind来解决字符串转日期类型
  5. 关于异常的疑难解答:System.Runtime.InteropServices.COMException
  6. 10_RHEL安装搜狗输入法
  7. 异步消息处理机制——Handler用法
  8. Linux下安装Wireshark
  9. graph driver-device mapper-04libdevmapper基本操作
  10. JQuery EasyUI combobox(下拉列表框)
  11. 安卓笔记-- popupwindow back键不消失的问题
  12. Unity的资源管理
  13. Linux ACL 权限
  14. python3 列表list
  15. Hbase学习笔记——基本CRUD操作
  16. Redux和React-Redux的实现(二):Provider组件和connect的实现
  17. 在asp.net中执行存储过程(转)
  18. Unity下的ECS框架 Entitas简介
  19. 深入理解JavaScript系列(17):面向对象编程之概论
  20. 01_常用的MIME类型

热门文章

  1. Spring单例 和 Scope注解
  2. CodeForces - 725D Contest Balloons 贪心
  3. Highmaps网页图表教程之绘图区显示标签显示数据标签定位
  4. [ 原创 ] Java基础2--构造方法的继承和重载
  5. 安卓手机安装 Charles 证书
  6. zookeeper【5】分布式锁
  7. 撩课-Java每天5道面试题第13天
  8. python开发_xml.dom_解析XML文档_完整版_博主推荐
  9. tyvj 1044 数字三角形 记忆化搜索
  10. opencv hog算子