# 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 head == None: return None dummy=ListNode(0) dummy.next=head start=dummy while start.next: end=start for i in range(k-1): end=end.next if end.next == None: return dummy.next res=self.reverse(start.next,end.next) start.next=res[0] start=res[1] return dummy.next def reverse(self,start,end): newHead=ListNode(0) newHead.next=start while newHead.next != end: tmp=start.next start.next=tmp.next tmp.next=newHead.next newHead.next=tmp return [end,start]
@link http://www.cnblogs.com/zuoyuan/p/3785555.html