题解 | #链表中的节点每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      





全部评论

相关推荐

10-25 00:32
香梨想要offer:感觉考研以后好好学 后面能乱杀,目前这简历有点难
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务