leetcode -- Reverse Nodes in k-Group -- 经典题目,要重写

来源:互联网 发布:天行加速器 for mac 编辑:程序博客网 时间:2024/05/01 16:45

https://leetcode.com/problems/reverse-nodes-in-k-group/

思路很简单,复习的时候再写一遍
http://www.cnblogs.com/zuoyuan/p/3785555.html

http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html

自己的code,自己可以写出来,有点慢,多写几次。在reverseList的时候,要注意先把tail.next置为None

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def reverseList(self, head, tail):        last, cur = None, head        new_tail = head        tail.next = None#这里注意进来先把tail.next置为None        while cur:            tmp = cur.next            cur.next = last            last = cur            cur = tmp        new_head = last        return new_head, new_tail    def reverseKGroup(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if not head: return None        if k == 1: return head        cur = head        dummy = ListNode(0)        last_tail = dummy        while cur:            count = 0            h = cur            pre = None            while cur and count < k:                pre = cur                cur = cur.next                count += 1            t = pre            if count == k:                new_h, new_t = self.reverseList(h, t)                print (h.val, t.val, new_h.val, new_t.val)            else:                new_h, new_t = h, t            last_tail.next = new_h            last_tail = new_t        return dummy.next
0 0
原创粉丝点击