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.
Solution
/**
* 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) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode prev = dummyNode;
for(int i = 1; i < m; i ++) {
prev = prev.next;
}
ListNode cur = prev.next;
ListNode speical = cur;
if (cur.next == null) {
return dummyNode.next;
} else {
cur = cur.next;
}
for(int i = m; i < n; i ++) {
ListNode temp = cur.next;
ListNode prevNext = prev.next;
prev.next = cur;
cur.next = prevNext;
speical.next = temp;
cur = temp;
}
return dummyNode.next;
}
}