25. Reverse Nodes in k-Group

昨天写的递归有点傻,嗯,没注意到k值,改了一下,代码如下:

# 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
        """
        p = head
        stack = []
        m = k
        while p and m:
            stack.append(p)
            m -= 1
            p = p.next
        if m > 0:
            return head
        newhead = ListNode(0)
        q = newhead
        while stack:
            q.next = stack.pop()
            q = q.next
        q.next = self.reverseKGroup(p, k)
        return newhead.next

第二种连接的办法,真的很6

# 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):
        dummy = jump = ListNode(0)
        dummy.next = l = r = head
    
        while True:
            count = 0
            while r and count < k:   # use r to locate the range
                r = r.next
                count += 1
            if count == k:  # if size k satisfied, reverse the inner linked list
                pre, cur = r, l
                for _ in range(k):
                    cur.next, cur, pre = pre, cur.next, cur  # standard reversing
                jump.next, jump, l = pre, l, r  # connect two k-groups
            else:
                return dummy.next

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