题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
O(n), O(n/k)
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @param k int整型 # @return ListNode类 # class Solution: def reverseKGroup(self , head , k ): # write code here def reverse(a, b): cur, nxt = a, a pre = None while cur!=b: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre if not head: return a,b = head, head for i in range(k): if not b: return head b = b.next newHead = reverse(a, b) a.next = self.reverseKGroup(b, k) return newHead