每日一练 | Day 6

92. 反转链表 II

题目链接

https://leetcode.cn/problems/reverse-linked-list-ii/

相关算法

链表

题目描述

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

数据范围:

  • 链表中节点数目为 n
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

解题思路

链表题有个特点,只要舍得定义临时变量,就能较轻松的做出来。今天这题是调整了反转链表,改为部分反转,对于这个需求,我们可以通过头插和尾插法相结合来实现。已知在 [left, right] 区间处需要进行反转操作,我们可以在小于 left 的地方进行尾插操作,在反转区间内进行头插操作,最后在大于 right 的地方进行尾插即可。题目中需要注意进行完头插操作后,此时的临时头结点还是开始头插操作时的位置,我们需要把它移动到链表的最后再开始进行尾插操作。

完整代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode(0, null);
        // 记录新链表节点位置
        ListNode temp = newHead;
        // 记录原链表节点位置
        ListNode pNode = head;
        int count = 1;
        while (count < left) {
            ListNode next = pNode.next;
            pNode.next = temp.next;
            temp.next = pNode;
            pNode = next;
            temp = temp.next;
            count++;
        }
        while (count <= right && pNode != null) {
            ListNode next = pNode.next;
            pNode.next = temp.next;
            temp.next = pNode;
            pNode = next;
            count++;
        }
        while (temp.next != null) {
            temp = temp.next;
        }
        while (pNode != null) {
            ListNode next = pNode.next;
            pNode.next = temp.next;
            temp.next = pNode;
            pNode = next;
            temp = temp.next;
        }
        return newHead.next;
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值