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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m == n) {
return head;
}
ListNode tmpA = head;
ListNode tmpBegin = null;
ListNode lastNow = null;
ListNode res = head;
if(m > n) {
int tmp = m;
m = n;
n = tmp;
}
int index=1;
while(index<=n) {
if(index==m) {
tmpBegin = tmpA;
lastNow = tmpA;
tmpA = tmpA.next;
}else if(index>m) {
ListNode now = tmpA;
ListNode tAfter = now.next;
now.next = lastNow;
tmpBegin.next = tAfter;
tmpA = tmpBegin.next;
lastNow = now;
}else {
tmpA = tmpA.next;
}
index++;
if(index<m) {
res = res.next;
}
}
if (m == 1) {
return lastNow;
} else {
res.next = lastNow;
return head;
}
}
}
用3个节点进行替换如1-2-3-4-5中先找出节点2为(tmpBegin不会改变)起始节点,3为当前节点 旋转后变为1-3-2-4-5,此时上一个开始节点(lastNow)变为节点3 ,在通过指定 now.next = lastNow ; tmpBegin.next = tAfter; 变为1-4-3-2-5
(lastNow为上一次旋转后的起始节点 第一次为2 旋转后为3 在旋转后变为4)