leetcode 之 Reorder List
2014-04-22 15:52
295 查看
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.
思路:首先找到链表的中间节点,从中间断开链表,得到l1,l2;反转链表l2,然后顺序的将l2的节点插入到l1中;每隔一个节点插入一个。
源代码如下:
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
思路:首先找到链表的中间节点,从中间断开链表,得到l1,l2;反转链表l2,然后顺序的将l2的节点插入到l1中;每隔一个节点插入一个。
源代码如下:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null) return ; ListNode pslow = head, pfast = head; while(pfast != null && pfast.next != null){ pslow = pslow.next; pfast = pfast.next.next; } ListNode midNode = pslow.next; pslow.next = null; ListNode secondNode = reverse(midNode); pslow = head; pfast = secondNode; while(pslow.next != null && pfast != null) { midNode = pfast; pfast = pfast.next; midNode.next = pslow.next; pslow.next = midNode; pslow = pslow.next.next; } if(pslow.next == null) pslow.next = pfast; } ListNode reverse(ListNode head){ if(head == null || head.next == null) return head; ListNode current = head.next; head.next = null; while(current != null) { ListNode tmpNode = current; current = current.next; tmpNode.next = head; head = tmpNode; } return head; } }
相关文章推荐
- Android TabHost的使用
- SVN 提交出错:Attempted to lock an already-locked dir
- 【Lucene3.6.2入门系列】第02节_针对索引文件的CRUD
- Path Sum II
- 脚本抓取邮编
- 计算几何学习之半平面交
- 2014-第九周项目三
- 判断各种网络的连接状态
- 锁链运动
- java Servlet和tomcat
- 克服敲代码之“痒”
- C++ - 内置类型的最大值宏定义
- DayDayUp之HTML5学习笔记 二 使用header、aside、section、footer实现一个简单的界面
- 简单几步让CentOS系统时间同步
- 从零开始编写自己的C#框架(3)——开发规范(转)
- pyDBGeng bugfix
- html里,如何去掉点击map里area的边框
- non-numeric second argument to `wordlist' function
- 查看端口占用情况
- mysql str_to_date