链表区间指定反转

1、前差反转

/*
public class ListNode
{
    public int val;
    public ListNode next;
    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}
*/

public class Solution
{
    public ListNode ReverseBetween(ListNode head, int m, int n)
    {
        if (head == null || m == n)
            return head;

        // 创建虚拟头节点以处理m=1的情况
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;

        // 移动到前驱节点(m-1的位置)
        for (int i = 0; i < m - 1; i++)
            pre = pre.next;

        ListNode start = pre.next;  // 反转区间的第一个节点
        ListNode then = start.next; // 当前要处理的节点

        // 反转m到n的部分,共n-m次操作
        for (int i = 0; i < n - m; i++)
        {
            start.next = then.next; // 将then的下一个节点保存到start.next
            then.next = pre.next;   // 将then插入到pre之后
            pre.next = then;
            then = start.next;      // 更新then为下一个待处理节点
        }

        return dummy.next;
    }
}

2、指向反转

using System;
using System.Collections.Generic;

/*
public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode (int x)
    {
        val = x;
    }
}
*/

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (m == n) {
            return head;
        }


        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode begin = null;
        ListNode beginPrev = null;
        ListNode end = null;
        ListNode endAffter = null;
        ListNode moveNode = dummy;
        for (int i = 0; i < m - 1; i++) {
            moveNode = moveNode.next;
        }
        beginPrev = moveNode;
        moveNode = moveNode.next;
        begin = moveNode;
        beginPrev.next = null;

        for (int i = 0; i < n - m; i++) {
            moveNode = moveNode.next;
        }
        end = moveNode;
        endAffter = moveNode.next;
        end.next = null;

        ListNode prev = endAffter;
        ListNode curr = begin;

        while (curr != null) {
            ListNode nextNode = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextNode;

        }
        beginPrev.next = prev;

        return dummy.next;

    }
}

 

posted @ 2025-03-18 22:53  燕钰达  阅读(10)  评论(0)    收藏  举报