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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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(head==null || head.next==null) return head;
ListNode cur = head, pre = null;
while(m>1){
pre = cur;
cur = cur.next;
--n;
--m;
}
ListNode con = pre, tail = cur;
while(n>0){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
--n;
}
if(con!=null){
con.next = pre;
}else{
head = pre;
}
tail.next = cur;
return head;
}
}