LeetCode Reverse Linked List II
2015-08-22 05:20
429 查看
原题链接在这里:https://leetcode.com/problems/reverse-linked-list-ii/
本题是Reverse Linked List的拓展。
基本思路和Reverse Linked List的Method 2 相似 扩展的地方在于本题限定了reverse的范围。
需先找到reverse范围的前一个点; 翻转时while loop走一次,翻转一个点,所以用一个计数器i 来限定接下来翻转的次数知道 i<n-1.
翻转完得到的的cur是翻转后的表头,把它连载mark的后面即可。
Note: 1. 再找mark时有corner case,e.g. [2,5],1,2. mark应该是2前面一个点,所以需要加一个dunmy head. i 从0开始计数。
2. 当m==length时,mark.next == null 需单独讨论,否则下面直接用mark.next会出错。
3. 返回的应该是dunmy.next.
AC Java:
本题是Reverse Linked List的拓展。
基本思路和Reverse Linked List的Method 2 相似 扩展的地方在于本题限定了reverse的范围。
需先找到reverse范围的前一个点; 翻转时while loop走一次,翻转一个点,所以用一个计数器i 来限定接下来翻转的次数知道 i<n-1.
翻转完得到的的cur是翻转后的表头,把它连载mark的后面即可。
Note: 1. 再找mark时有corner case,e.g. [2,5],1,2. mark应该是2前面一个点,所以需要加一个dunmy head. i 从0开始计数。
2. 当m==length时,mark.next == null 需单独讨论,否则下面直接用mark.next会出错。
3. 返回的应该是dunmy.next.
AC Java:
/** * 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(head == null || head.next == null){ return head; } ListNode dunmy = new ListNode(0); dunmy.next = head; ListNode mark = dunmy; int i = 0; while(i < m-1){ mark = mark.next; i++; } if(mark.next == null){ return dunmy.next; } ListNode cur = mark.next; ListNode tail = mark.next; ListNode pre; ListNode temp; while(tail.next != null && i < n-1){ pre = cur; cur = tail.next; temp = cur.next; cur.next = pre; tail.next = temp; i++; } mark.next = cur; return dunmy.next; } }
相关文章推荐
- LeetCode Reverse Linked List II
- POJ 1188 解题报告
- LeetCode_Surrounded Regions
- Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)
- Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)
- 在交互式shell脚本中创建对话框
- Atom编辑器折腾记_(14)JQ代码片段补全(插件:Jquery-snippets)
- Atom编辑器折腾记_(14)JQ代码片段补全(插件:Jquery-snippets)
- LeetCode Reverse Linked List
- Leetcode_Palindrome Partitioning II
- LeetCode Reverse Linked List
- [LeetCode#47]Permutations II
- shell脚本中一些特殊符号
- 使用wget 命令下载JDK的方法
- 操作队列
- XPath入门教程
- NGUI的代码控制
- 跳台阶解析【剑指Offer】
- uva11992区间修改线段树
- Mybatis 中 if test字符串比较问题