Reverse Linked List II 解答
2015-10-28 22:08
381 查看
Question
Reverse a linked list from position m to n. Do it in-place and in one-pass.For example:
Given
1->2->3->4->5->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution
Four pointers:Dummy node, pre, start, then, tmp
First, we find the position to start reversal.
Key point here is to use Dummy node, and pre points the (m - 1) position.
Then, we use three pointers, start, then, tmp to implement reversal. Just the same way as Reverse Linked List.
Several points to note here:
1. Move (m - 1) steps to get pre position
2. Move (n - m) steps to implement reversal
3. Link reversed sub-list with original unreversed sub-lists.
In-place and in one-pass.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (m == n || head == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy, start = dummy, then = dummy, tmp = dummy; // Move pre to (m - 1) position for (int i = 0; i < (m - 1); i++) { pre = pre.next; } // Start = m start = pre.next; then = start.next; start.next = null; // Move (n - m) steps for reverse for (int i = 0; i < (n - m); i++) { tmp = then.next; then.next = start; start = then; then = tmp; } pre.next.next = then; pre.next = start; return dummy.next; } }
相关文章推荐
- 专访腾讯徐汉彬:日请求高达3.5亿+平台的架构设计及演变
- Android之RecyclerView之空数据提示
- fl2440开发板hello world模块驱动编写
- 大道至简第五章读后感
- 一个类有多大
- 内部排序-交换式排序-冒泡排序法
- 【JAVA核心技术卷一】Inner Class内部类&Proxy代理
- Android多媒体—图片技术
- 最最最基础的软件测试
- Apache htpasswd命令
- JPA学习笔记-映射单向一对多的关联关系
- SpringMVC 过滤器Filter使用解析
- sed在行首或者行尾添加内容
- c# ListView的网格简单用法
- sed在行首或者行尾添加内容
- 稀疏矩阵快速转置
- javascript基础之prompt
- Leetcode -- Shortest Palindrome
- RHCS集群理论暨 最佳实践
- Scala并行