反转链表

in 知识共享 with 0 comment

题目来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

输入: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

本人提交代码:

/**
 * 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* reverseList( ListNode* start, ListNode* end )
    {
        ListNode* pPrev = NULL;
        while ( start != end )
        {
            ListNode* next = start->next;
            start->next = pPrev;
            pPrev = start;
            start = next;
        }
        start->next = pPrev;
        return start;
    }

    ListNode* reverseBetween(ListNode* head, int left, int right) {
        int index = 0;
        ListNode* node = head;
        ListNode* pPrev = NULL;
        ListNode* pStart = NULL;
        while( node )
        {
            if ( ++index == left )
                break;

            pPrev = node;
            node = node->next;
        }
        pStart = node;

        node = pStart;
        ListNode* pEnd = NULL;
        index = 0;
        while( node )
        {
            if ( ++index == right - left + 1 )
                break;

            pEnd = node;
            node = node->next;
        }
        pEnd = node;
        
        ListNode* pEndNext = pEnd->next;
        if ( pPrev )
            pPrev->next = reverseList( pStart, pEnd );
        else
            head = reverseList( pStart, pEnd );

        pStart->next = pEndNext;
        return head;
    }
};
Responses