题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

# 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):
            prev, curr, nxt = None, a, a
            while curr!=b:
                nxt = curr.next
                curr.next = prev
                prev = curr
                curr = nxt
            return prev
        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      





全部评论

相关推荐

11-09 12:17
清华大学 C++
out11Man:小丑罢了,不用理会
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
10-15 14:22
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务