给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dum = new ListNode(-1);
dum.next = head;
ListNode leftNode1 = dum;
ListNode rightNode2 = dum;
while(left > 1){
leftNode1 = leftNode1.next;
left--;
}
ListNode leftNode2= leftNode1.next;
while(right > 0){
rightNode2 = rightNode2.next;
right--;
}
ListNode rightNode1 = rightNode2.next;
// 将需要反转的链表的最后一个节点的next=null
rightNode2.next = null;
recerse(leftNode2);
leftNode1.next = rightNode2;
leftNode2.next = rightNode1;
return dum.next;
}
// 反转整个链表
public void recerse(ListNode head){
ListNode newhead = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = newhead;
newhead = cur;
cur = next;
}
}
}