LeetCode 92. Reverse Linked List II
原题链接在这里:https://leetcode.com/problems/reverse-linked-list-ii/
题目:
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.
题解:
本题是Reverse Linked List的拓展。
基本思路类似Reverse Linked List的iteration.
需先找到reverse范围的前一个点记为mark. 翻转时while loop走一次,翻转一个点,所以用一个计数器i 来限定接下来翻转的次数知道 i<n.
翻转完得到的的cur是翻转后的表头,把它连载mark的后面.
Note: 当m==length时,mark.next == null 需单独讨论,否则下面tail = mark.next, 直接用tail.next会NRE.
Time Complexity: O(n), one pass.
Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode reverseBetween(ListNode head, int m, int n) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode mark = dummy; 18 int i = 1; 19 while(i<m){ 20 mark = mark.next; 21 i++; 22 } 23 24 if(mark.next == null){ //tail = mark.next, tail.next will throw NRE without this check 25 return dummy.next; 26 } 27 28 ListNode tail = mark.next; 29 ListNode cur = mark.next; 30 ListNode pre; 31 ListNode temp; 32 while(tail.next != null && i<n){ 33 pre = cur; 34 cur = tail.next; 35 temp = cur.next; 36 cur.next = pre; 37 tail.next = temp; 38 i++; 39 } 40 mark.next = cur; 41 return dummy.next; 42 } 43 }