1. 程式人生 > >python leetcode 25. Reverse Nodes in k-Group

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]