25. Reverse Nodes in k-Group

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了25. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

# 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):
        pre, pre.next = self, head
        n = k
        pre_last_node, p1 = pre, pre.next
        while pre:
            if n == 0:
                p2 = p1.next
                p1.next = None
                for _ in xrange(k - 1):
                    p3 = p2.next
                    p2.next = p1
                    p1 = p2
                    p2 = p3
                n = k
                pre_last_node.next, p1 = p1, p2
            pre = pre.next
            n -= 1
        if n > 0:
            pre_last_node.next = p1
        return self.next

def generate(ret_list , value):
    t = ListNode(value)
    ret_list.next = t
    return ret_list.next
t = ListNode(0)
reduce(generate, [1, 2, 3], t)
# test
import time
s = Solution()
start = time.clock()
r = s.reverseKGroup(t.next, 2)
while r:
    print r.val,
    r = r.next
end = time.clock()
print cpu time :  + str(end - start)

 

以上是关于25. Reverse Nodes in k-Group的主要内容,如果未能解决你的问题,请参考以下文章

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group(js)

LeetCode - 25. Reverse Nodes in k-Group