题目92. 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.
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || head.next == null){
return head;
}
if(m == n){
return head;
}
ListNode tempHead = new ListNode(1);
tempHead.next = head;
ListNode reverseHead = null;
ListNode tail = null;
ListNode node = tempHead;
ListNode tempNode = null;
int curNum = 0;
while(node != null){
tempNode = node.next;
if(curNum == (m - 1)){
reverseHead = node;
tail = reverseHead;
}else if(curNum >= m && curNum <= n){
node.next = reverseHead.next;
reverseHead.next = node;
tail = tail.next;
}else if(curNum > n){
break;
}
node=tempNode;
curNum ++;
}
tail.next = node;
return tempHead.next;
}
}