码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 25. K 个一组翻转链表

时间:2020-05-17 01:15:32      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:ext   ever   商业   group   bre   leetcode   获得   天都   tar   

方法一:;来自大佬

public ListNode reverseKGroup(ListNode head, int k) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;

    ListNode pre = dummy;
    ListNode end = dummy;

    while (end.next != null) {
        for (int i = 0; i < k && end != null; i++) end = end.next;
        if (end == null) break;
        ListNode start = pre.next;
        ListNode next = end.next;
        end.next = null;
        pre.next = reverse(start);
        start.next = next;
        pre = start;

        end = pre;
    }
    return dummy.next;
}

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

作者:reals
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/tu-jie-kge-yi-zu-fan-zhuan-lian-biao-by-user7208t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

前几天都在gy,在外面都没时间写拉,补回来

[LeetCode] 25. K 个一组翻转链表

标签:ext   ever   商业   group   bre   leetcode   获得   天都   tar   

原文地址:https://www.cnblogs.com/doyi111/p/12902957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!