1. 反转链表 II
    中等
    1.5K
    相关企业
    给你单链表的头指针 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

进阶: 你可以使用一趟扫描完成反转吗?

题解

首先跑一遍找到最左端和最右端的指针,然后把中间这段反转一下就行了,最后再把中间反转的链表和最左端和最右端的指针连接就OK了。

AC代码

/**
 * 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) 
    {
        if(head==NULL||head->next==NULL||left==right)return head;
        ListNode * new_head = new ListNode();
        //为了避免临界情况
        new_head->next = head;
        left += 1;
        right += 1;

        ListNode * p = new_head;
        ListNode * left_head=NULL, * right_head=NULL;
        int index = 0;
        while(p!=NULL)
        {
            index += 1;
            if(index+1==left)
            left_head = p;
            if(index-1==right)
            right_head = p;
            p = p->next;
        }
        ListNode * last = left_head->next;
        ListNode * cur = last->next;
        last->next = NULL;
        while(cur!=NULL&&cur->next!=NULL)
        {
            ListNode * next = cur->next;
            if(next==right_head)break;
            cur->next = last;
            last = cur;
            cur = next;
        }
        cur->next = last;
        left_head->next = cur;
        while(cur->next!=NULL)
        {
            cur = cur->next;
        }
        cur->next = right_head;
        return new_head->next;
    }
};

在这里插入图片描述

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐