码迷,mamicode.com
首页 > 其他好文 > 详细

25. Reverse Nodes in k-Group

时间:2016-03-04 00:41:43      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

# 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

标签:

原文地址:http://www.cnblogs.com/zhuifengjingling/p/5240162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!