专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

leetcode 反转链表及每K个一组反转链表精简解答

一、单链表反转。

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

解答
(1) 非递归版本

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

(2) 递归版本

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

二、单链表中部分反转

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:
1 ≤ m ≤ n ≤ 链表长度。

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode cur = dummyHead;
        for (int i = 1; i < m; i++) {
            cur = cur.next;
        }
        ListNode tail = cur.next;
        ListNode pre = null;
        for (int i = m; i <= n; i++) {
            ListNode next = tail.next;
            tail.next = pre;
            pre = tail;
            tail = next;
        }
        cur.next.next = tail;
        cur.next = pre;
        return dummyHead.next;
    }
}

三、K个一组反转链表

给你一个链表,每k个节点一组进行翻转,请你返回翻转后的链表。

k是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是k的整数倍,那么请将最后剩余的节点保持原有顺序。

示例:

给你这个链表:1->2->3->4->5

当k= 2 时,应当返回: 2->1->4->3->5

当k= 3 时,应当返回: 3->2->1->4->5

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null)
            return head;
        ListNode tail = head;
        for (int i = 0; i < k; i++) {
            if (tail == null)
                return head;
            tail = tail.next;
        }
        ListNode newHead = reverse(head,tail);
        head.next = reverseKGroup(tail,k);
        return newHead;
    }

    private ListNode reverse(ListNode head, ListNode tail) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != tail) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

文章永久链接:https://tech.souyunku.com/27973

未经允许不得转载:搜云库技术团队 » leetcode 反转链表及每K个一组反转链表精简解答

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们