Reverse a linked list from position m to n.
Example
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @oaram m and n
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m , int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy, second = null;
while(m > 1) {
first = first.next;
m--;
n--;
}
second = first.next;
first.next = null;
ListNode secondHead = null, firstEnd = second;
while(n > 0) {
secondHead = second.next;
ListNode tmp = first.next;
first.next = second;
second.next = tmp;
second = secondHead;
n--;
}
firstEnd.next = secondHead;
return dummy.next;
}
}