LeetCode 92.反转链表II

发布时间:2023年12月18日

题目

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

方法:灵神 反转链表

代码:

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(0, head), p0 = dummy;
        int n = left - 1;
        while (n-- > 0) {
            p0 = p0.next; // p0 保存开始翻转的前一个节点,后面操作需要用到
        }
        ListNode pre = null, cur = p0.next;
        for (int i = 0; i < (right - left + 1); i++) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        p0.next.next = cur;
        p0.next = pre;
        return dummy.next;
    }
}

文章来源:https://blog.csdn.net/qq_57349657/article/details/135024533
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。