92. 反转链表 II + 有左右边界的翻转链表 + 翻转

92. 反转链表 II

LeetCode_92

题目描述

解法一:穿针引线法-模拟的思路

  1. 首先确定一个左边界start表示翻转开始的起始点。
  2. 在左右边界之间不断修改next指针指向下一个结点。
  3. 当遍历到右边界的下一个字符时开始翻转这一整段的链表。
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode pre = null, now = head;
        int cnt = 0;
        ListNode start = null, end = null;
        while(now != null){
            cnt++;
            ListNode temp = now.next;
            if(cnt == left){
                start = now;
                now.next = pre;
            }else if(cnt == right+1){
                if(start.next != null){
                    start.next.next = pre;
                    start.next = now;
                }else{
                    start.next = now;
                    head = pre;
                }
                return head;
            }else if(cnt > left && cnt <= right){
                now.next = pre;
            }
            pre = now;
            now = temp;
        }
        if(cnt == right){
            if(start.next != null){
                start.next.next = pre;
                start.next = null;
            }else{
                start.next = null;
                head = pre;
            }
        }
        return head;
    }
}

方法二:类似于插入结点的方法穿针引线

/**
 * 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 vnode = new ListNode(-1);//虚拟结点
        vnode.next = head;

        ListNode pre = vnode;
        //让pre指向翻转区间的前一个结点
        for(int i=0; i<left-1; i++){
            pre = pre.next;
        }
        ListNode current = pre.next;
        //依次翻转区间的结点,不断把下一个结点移动到开始区间的第一个位置
        for(int i=0; i<right - left; i++){
            ListNode temp = current.next;
            current.next = temp.next;
            temp.next = pre.next;
            pre.next = temp;//注意以上两行不能写成pre.next = temp; temp.next = current;因为这里的current不一定是最接近起始点的位置,current会改变的
        }
        return vnode.next;
    }
}
posted @   Garrett_Wale  阅读(93)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2020-03-15 蓝桥杯-分巧克力(暴力+二分优化)
2020-03-15 蓝桥杯-包子凑数(完全背包+不定方程的数学性质+多个数的最大公因数)
2020-03-15 蓝桥杯-正则表达式
点击右上角即可分享
微信分享提示