0
点赞
收藏
分享

微信扫一扫

LeetCode 92. 反转链表 II

潇湘落木life 2022-03-13 阅读 53

具体思路:

反转链表,标准;

具体代码:

/**
 * 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:
    void fun(ListNode* root, ListNode* pre,ListNode* &newhead) {
        if (!root)
            return;
        if (!root->next) {
            newhead = root;
        }
        fun(root->next, root, newhead);
        root->next = pre;
    }

    ListNode* reverseBetween(ListNode* head, int left, int right) {
        if (left == right)
            return head;
        ListNode* phead = new ListNode(-1);
        phead->next = head;
        ListNode* pre = phead;
        ListNode* tail = phead;
        for (int i = 1; i < left; i++) {
            pre = pre->next;
        }
        tail = pre->next;
        for (int i = 0; i < right - left; i++) {
            tail = tail->next;
        }
        ListNode* last = tail->next;
        tail->next = nullptr;
        ListNode* temp = pre->next;
        ListNode* rhead = nullptr;
        fun(pre->next, nullptr, rhead);
        pre->next = rhead;
        temp->next = last;
        return phead->next;
    }
};
举报

相关推荐

0 条评论