92.反转链表II
问题:给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表。
示例:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
输入:head = [5], left = 1, right = 1
输出:[5]
思路:
递归
前left个节点保持不动,找到第left个节点后,反转[left, right]的子链表。
class Solution {
private ListNode successor = null;
public ListNode reverseBetween(ListNode head, int left, int right) {
if(left == 1){
//走到了第left个节点,将问题转化为反转前n个节点
return reverseN(head, right);
}
//前left个节点保持不动
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
}
//反转前n个节点
private ListNode reverseN(ListNode node, int n){
//第n个元素,记录其后驱节点,因为第n个节点后可能还有元素
if(n == 1){
successor = node.next;
return node;
}
ListNode last = reverseN(node.next, n - 1);
node.next.next = node;
//将反转后的子链表和 后半段链表接上
node.next = successor;
return last;
}
}
迭代 头插法
结合画图会更容易理解,还是需要细节,比如两个for循环的边界
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
for(int i = 0; i < left - 1; i++){
pre = pre.next;
}
//从cur节点开始反转
ListNode cur = pre.next;
for(int i = 0; i < right - left; i++){
//记录当前节点的后继节点
ListNode next = cur.next;
//将当前节点的后继节点指向 后继节点的后继节点
cur.next = next.next;
//下面两步就是将当前节点的后继节点头插法插入到前面
next.next = pre.next;
pre.next = next;
//这种写法不用让cur再后移一位,因为已经将其后继节点指向了下一个需要 头插 的节点
}
return dummy.next;
}
}
整理思路,记录博客,以便复习。若有误,望指正~