Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
// (p) -> 1->2->3->4->5->NULL
// 1 2 3 4 5
// p1 p2
// 1<-2<-3<-4
// (p) -> 1->4->3->2->5->NULL
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode curr = head;
int p = 1;
while (p < m) {
prev = curr;
curr = curr.next;
p ++;
}
ListNode p1 = prev;
ListNode p2 = curr;
while (p <= n) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
p ++;
}
p1.next = prev;
p2.next = curr;
return dummy.next;
}
}