题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

import java.util.*;

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

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

    private void ReverseList(ListNode head) {
        if (head == null ||
                head.next == null) { //判断链表为空或长度为1的情况
            // return head;
        }

        ListNode pre = null;
        ListNode cur = head;
        ListNode tmp = null; //记录当前节点的下个节点


        while (cur != null) {
            tmp = cur.next;  //记录当前节点的下一个节点
            cur.next = pre;  //让当前节点的next指向前一个节点
            pre = cur;       //pre往前移动一位
            cur = tmp;       //当前节点往后移动一位
        }
        // return pre;
    }
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if (m == n) {
            return head;
        }
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode cur = head;
        ListNode leftNode = null; // 需要反转的子链表的头
        ListNode rightNode = null; // 需要反转的子链表的尾
        for (int i = 0; i < m - 1; i++) { // 跳到指定的节点的位置
            pre = pre.next;
        }
        leftNode = pre.next;
        for (int i = 0; i < n; i++) {
            rightNode = cur;
            cur = cur.next;
        }
        pre.next = null;
        rightNode.next = null;

        ReverseList(leftNode);
        pre.next = rightNode;
        leftNode.next = cur;
        
        return dummyNode.next;

    }
}

中间的子链表断开后重新接回来的时候,需要记得leftNode和rightNode里存放的指针仍然分别是之前的“左节点”和“右节点”的,并不会因为反转了而变化,这也许是指针的知识比较晦涩的地方。

全部评论

相关推荐

xdm怎么说&nbsp;要被拷打了&nbsp;担心是KPI
丹田:面就完了,就当日薪四位数的大佬免费给给你面试。
点赞 评论 收藏
分享
06-11 13:34
门头沟学院 C++
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务