zoukankan      html  css  js  c++  java
  • 25. Reverse Nodes in k-Group

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

    If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For example,
    Given this linked list: 1->2->3->4->5

    For k = 2, you should return: 2->1->4->3->5

    For k = 3, you should return: 3->2->1->4->5

    AC代码:

    class Solution(object):
        def reverseKGroup(self, head, k):
            if k <= 1: return head
            pre, pre.next = self, head
            n = k
            pre_last_node, p1 = pre, pre.next
            while pre:
                if n == 0:
                    p2 = p1.next
                    # record first of one group, 
                    # value its next to None in case of forming a circle when len(head) % k == 0
                    first_temp, first_temp.next = p1, None
                    # insert every node behind head, then it can reverse
                    for _ in xrange(k - 1):
                        p3 = p2.next
                        p2.next = p1
                        p1 = p2
                        p2 = p3
                    n = k - 1
                    # now first_temp should be the last of current group, 
                    # and p1: first of current group, p2:first of next group
                    pre = p2
                    pre_last_node.next, pre_last_node, p1 = p1, first_temp, p2
                else:
                    n -= 1
                    pre = pre.next
            # needed when the number of last group less than k
            pre_last_node.next = p1
            return self.next

    难点:

    1.将链表逆序融合到问题中,增加了复杂度。

    2.游标前进的时候需要分组逆序。

    3.需要两个游标:外层游标循环所有节点,内层游标循环需要逆序的分组,故需要保存的节点较多,不仔细思考容易出错。

    注释已经在代码中比较详细了。Leetcode本题给的评级是Hard,其实只要细心一点,难度并不算太大。

  • 相关阅读:
    Algs4-2.2.1给出原地归并排序merge的排序过程
    Algs4-2.2.2给出自顶向下归并排序的排序过程
    Algs4-2.1.38不同类型的元素
    Algs4-2.1.36不均匀的数据
    Algs4-2.1.37部分有序
    Algs4-2.1.35不均匀的概率分布
    Algs4-2.1.34罕见情况
    升级python到2.7版本pip不可用
    随机验证码
    python文件操作
  • 原文地址:https://www.cnblogs.com/zhuifengjingling/p/5240162.html
Copyright © 2011-2022 走看看