题目描述
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
提示:
- 链表中节点数目为 n
- 1 <= n <= 500
- -500 <= Node.val <= 500
- 1 <= left <= right <= n
题解
1、新建头节点res,在left之前,所有节点依次添加res链表的最后。
2、到达left时,记录此时res的尾节点curRes。
3、从left到right之间的每个节点,利用头插法添加在curRes之后
4、添加之后,如果head还有剩余,curRes走到res链表结尾,curRes.next = head
5、最后返回res.next
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode res = new ListNode(), curHead = head, curRes = res;
int count = 0;
//left之前,按循序添加到res链表最后
while (count < left - 1){
curRes.next = head;
head = head.next;
curRes = curRes.next;
count++;
}
//此时curRes为res链表尾,curHead为head剩下的头节点
curRes.next = null;
curHead = head;
//开始反转,利用头插法把left到right之间的节点插入到curRes之后
while (count < right){
head = head.next;
curHead.next = curRes.next;
curRes.next = curHead;
curHead = head;
count++;
}
//如果head链表还有剩余,直接添加到res链表的最后
if (curHead != null){
while (curRes.next != null){
curRes = curRes.next;
}
curRes.next = curHead;
}
return res.next;
}
}