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.
一刷
思路:
翻转部分隔离出来,记录这部分之前的节点和之后的节点。然后翻转这部分,再和之前记录的两个节点连接起来就可以了。缺点:还是不够简洁,需要单独判断m=1的情况。希望二刷的时候能够改进。并且还要注意在某个区域内翻转时,dummy node的技巧。
Time Complexity - O(n), Space Complexity - O(1)
/**
* 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) return head;
ListNode prev;
if(m == 1) {
prev = new ListNode(-1);
prev.next = head;
}
else prev = find(head, m);
ListNode after = find(head, n+2);
ListNode rev = reverse(prev.next, after); //number of element to get reversed
prev.next = rev;
if(m == 1) return prev.next;
else return head;
}
private ListNode find(ListNode head, int m){
while(m>2){
head = head.next;
m--;
}
return head;
}
private ListNode reverse(ListNode head, ListNode tail){
ListNode dummy = new ListNode(-1);
dummy.next = tail;
ListNode tmp = new ListNode (-1);
while(head!=tail){
tmp = head.next;
head.next = dummy.next;
dummy.next = head;
head = tmp;
}
return dummy.next;
}
}
二刷:
/**
* 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) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i=0;i<m-1; i++) pre = pre.next;//pre.next is the start point
ListNode start = pre.next;
ListNode then = start.next;
for(int i=0; i<n-m; i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;//the next to add in
then = start.next;
}
return dummy.next;
}
}