【LeetCode92】反转链表 II(头插法)

本文详细介绍了如何使用头插法在O(n)的时间复杂度内反转链表的指定区间。通过设置三个指针pre、cur、next,逐步调整节点的连接关系,实现了对链表部分区间的反转。同时给出了C++和Python两种语言的代码实现,展示了反转链表的通用技巧。此外,还提供了一个反转链表打印的辅助函数,加深对链表操作的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.题目

在这里插入图片描述

2.思路

头插法,关键代码:

        for(int i = 0; i < right - left; i++){
            next = cur->next;
            cur->next = next->next;
            pre->next = next;
            next->next =cur;
        }

三个指针的顺序:pre,cur,next
(1)将cur的next指针指向next的下一个结点;
(2)把next的next指针指向pre的下一个结点;
(3)最后,把pre的next指针指向next结点。
就这样实现时间复杂度O(n)O(n)O(n)遍历一次链表,就将left到right的部分进行反转了。

3.代码(C++)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode *DummyNode = new ListNode(-1);//惯用做法,防止left为1
        DummyNode->next = head;
        ListNode *pre = DummyNode;
        for(int i = 0; i < left - 1; i++){//left从1开始的
            pre = pre->next;
        }
        //pre到达要处理部分的前一个结点
        ListNode *cur = pre->next;
        ListNode *next;
        for(int i = 0; i < right - left; i++){
            next = cur->next;
            cur->next = next->next;
            next->next = pre->next;//最关键
            pre->next = next;
        }
        return DummyNode->next;
    }
};

4.代码(python)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
        DummyNode = ListNode(-1)
        DummyNode.next = head
        pre = DummyNode
        for _ in range(left - 1):
            pre = pre.next
        
        cur = pre.next
        for _ in range(right - left):
            next = cur.next
            cur.next = next.next
            next.next = pre.next
            pre.next = next
        return DummyNode.next

可以看一道类似的,反转链表,不过没给出左右的指针:
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        if(!head){
            return {};
        }
        vector<int> vec = reversePrint(head->next);
        vec.push_back(head->val);
        return vec;
    }
};
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山顶夕景

小哥哥给我买个零食可好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值