给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
代码:
public static ListNode reverseBetween(ListNode head, int left, int right) {
int i=1;
ListNode nodeleft,noderight,p =head,leftfirst =null,p1 =null,p2 =null;
while(p!=null) {
if(i==left-1) {
leftfirst=p;
}
else if(i==left) {
p2=p1=p;
p=p.next;
i++;
continue;
}else if(i>left&&i<right) {
nodeleft=p;
p=p.next;
nodeleft.next=p1;
p1=nodeleft;
i++;
continue;
}else if(i==right) {
noderight=p.next;
nodeleft=p;
nodeleft.next=p1;
p1=nodeleft;
if(leftfirst!=null){
leftfirst.next=p1;
}
p2.next=noderight;
if(left==1) {
head=p1;
}
break;
}
i++;
p=p.next;
}
return head;
}