题目
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
解
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
int count = 0;
ListNode p1 = dummy;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
count++;
if (count == left - 1) {
p1 = cur;
} else if (count == right) {
ListNode p2 = p1.next;
cur.next = null;
p1.next = null;
reverse(p2);
p2.next = next;
p1.next = cur;
break;
}
cur = next;
}
return dummy.next;
}
private void reverse(ListNode head){
if (head == null || head.next == null) {
return;
}
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
}
}