python leetcode 25. Reverse Nodes in k-Group

按着题意做即可,遍历找到所在位置再翻转

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        count=0 
        ans = ListNode(0)
        res=ans
        p=head
        q=p 
        while p:
            count+=1
            if count==k:
                p1=p.next
                p.next=None
                L=self.reverseL(q) 
                ans.next=L[0]
                ans=L[1]
                count=0
                p=p1
                q=p1 
            else:
                p=p.next
        ans.next=q
        return res.next
    def reverseL(self,head):
        p=head 
        q=head.next
        p.next=None 
        while q:
            r=q.next 
            q.next=p 
            p=q
            q=r
        return [p,head] 

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84864316