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 1:Iterative 找到位置后 依次reverse
思路可参考206题1a:http://www.jianshu.com/p/56353df45769
找到reverse前的位置,其余和206题1a相同,再link上即可
Time Complexity: O(N) Space Complexity: O(1)
Solution 2:Iterative 找到位置后 (前部)插入法reverse
思路可参考206题1b:http://www.jianshu.com/p/56353df45769
思路:前部插入法reverse: 1 -> 2 -> 3 -> 4
2 -> 1 -> 3 -> 4 再 3 -> 2 -> 1 -> 4 再 4 -> 3 -> 2 -> 1
找到reverse前的位置,其余和206题1b相同,再link上即可
Time Complexity: O(N) Space Complexity: O(1)
Solution1 Code:
class Solution1 {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
if(m == n) return head; // just in case
ListNode dummy = new ListNode(0);
dummy.next = head;
// find before position, which at the node before reversing
ListNode before = dummy;
for(int i = 0; i < m-1; i++) before = before.next;
// init
ListNode r_head = before.next; // a pointer to the beginning of a sub-list that will be reversed
ListNode cur = r_head;
ListNode prev = null; //(prev to cur every time)
// start reversing
for(int i = 0; i < n - m + 1; i++)
{
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
// relink
before.next = prev;
r_head.next = cur;
return dummy.next;
}
}
Solution2 Code:
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return null;
if(m == n) return head; // just in case
ListNode dummy = new ListNode(0);
dummy.next = head;
// find before position, which at the node before reversing
ListNode before = dummy;
for(int i = 0; i < m-1; i++) before = before.next;
// init
ListNode r_head = before.next; // a pointer to the beginning of a sub-list that will be reversed
ListNode cur = r_head;
ListNode post = null; //(right after cur every time)
// start reversing
for(int i = 0; i < n - m; i++)
{
post = cur.next;
cur.next = cur.next.next;
post.next = r_head;
r_head = post;
}
// relink r_head
before.next = r_head;
return dummy.next;
}
}