刷题-力扣-92. 反转链表 II

92. 反转链表 II

题目链接

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

题目描述

给你单链表的头指针 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

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

题目分析

  1. 根据题目描述反转链表里部分元素
  2. 把链表分为三部分,需要反转的前半段、反转的部分、需要反转的后半段
  3. 需要反转的部分存放在stack中,利用后进先出的原理反转链表
  4. 最后把需要反转的前半段、反转后的部分、需要反转的后半段,这三部分拼接起来

代码

/**
 * 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) {
        stack<ListNode*> listStack;
        ListNode* p = head;
        ListNode* front = nullptr;
        ListNode* rear = nullptr;
        int index = 1;
        while (p) {
            if (index == left - 1) front = p;
            if (index == right + 1) rear = p;
            if (index >= left && index <= right) listStack.push(p);
            index++;
            p = p->next;
        }
        if (front == nullptr) {
            head = listStack.top();
            listStack.pop();
            front = head;
        }
        while (!listStack.empty()) {
                front->next = listStack.top();
                listStack.pop();
                front = front->next;
            }
        front->next = rear;
        return head;        
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/14557972.html