LeetCode Reverse Nodes in k-Group

LeetCode解题之Reverse Nodes in k-Group

原题

将一个链表中每k个数进行翻转,末尾不足k个的数不做变化。

注意点:

  • 不允许修改节点的值
  • 只能用常量的额外空间

例子:

输入: head = 1->2->3->4->5, k = 2
输出: 2->1->4->3->5

输入: head = 1->2->3->4->5, k = 3
输出: 3->2->1->4->5

解题思路

这个题是Swap Nodes in Pairs的升级版。我们来看一下翻转k个节点要进行哪些操作,A->B->C->D->E,现在我们要翻转BCD三个节点。进行以下几步:

  1. C->B
  2. D->C
  3. B->E
  4. A->D
  5. 返回及节点B

上面做了两件事,把k个节点先翻转(1、2两步),再和前后两个节点连接起来(3、4两步)。

AC源码

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def reverseKGroup(self, head, k):
        """ :type head: ListNode :type k: int :rtype: ListNode """
        if not head or k <= 1:
            return head
        dummy = ListNode(-1)
        dummy.next = head
        temp = dummy
        while temp:
            temp = self.reverseNextK(temp, k)
        return dummy.next

    def reverseNextK(self, head, k):
        # Check if there are k nodes left
        temp = head
        for i in range(k):
            if not temp.next:
                return None
            temp = temp.next

        # The last node when the k nodes reversed
        node = head.next
        prev = head
        curr = head.next
        # Reverse k nodes
        for i in range(k):
            nextNode = curr.nex
            curr.next = prev
            prev = curr
            curr = nextNode
        # Connect with head and tail
        node.next = curr
        head.next = prev
        return node

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,链表,笔试)