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,其实只要细心一点,难度并不算太大。

你可能感兴趣的:(25. Reverse Nodes in k-Group)