每日一题:反转链表Ⅱ(LeetCode 92)

题目

给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表
示例:

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

解答

/**
 * 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* dummy = new ListNode(-1);
        dummy->next = head;

        ListNode* pre = dummy;
        ListNode* cur = head;

        //一直向后移动,直到找到left
        for(int i = 0; i < left-1; i++)
        {
            pre = cur;
            cur = cur->next;
        }

        //开始翻转结点
        for(int i  = 0; i < right-left; i++)
        {
            ListNode* tmp = cur->next;
            //第一次循环:2->4,第二次循环:2->5
            cur->next = cur->next->next;
            //第一次循环:3->2,第二次循环:4->3
            tmp->next = pre->next; 
            //第一次循环:1->3,第二次循环:1->4
            pre->next = tmp; 
        }

        return dummy->next;

    }
};
扫描关注程序区

有任何问题,请联系邮箱:support@progdomain.com

THE END
分享
二维码
打赏
海报
每日一题:反转链表Ⅱ(LeetCode 92)
题目 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。……
<<上一篇
下一篇>>