用栈做:
# 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 """ dummy=ListNode(0) p=dummy while True: count=k stack=[] tmp=head while count and tmp: stack.append(tmp) tmp=tmp.next count-=1 if count: p.next=head break while stack: p.next=stack.pop() p=p.next p.next=tmp head=tmp return dummy.next
执行用时 :32 ms, 在所有 python 提交中击败了95.97%的用户
内存消耗 :13.2 MB, 在所有 python 提交中击败了44.26%的用户
——2019.10.31