leetcode#25

==============================================================================

【id】#25

【title】Reverse Nodes in k-Group

【description】

【idea】

先设置一个dummy head,因为在链表反转时head可能会被改变顺序找不到头节点,所以先用一个假的头节点。

然后找到要反转的k个节点的左右边界l,r。

进行单链表的反转,这里用的非递归算法。

「单链表标准反转」

总之是要先将当前节点cur的下一个节点next记录下来,放在tmp,也就是tmp = cur.next ;然后当前节点连接到pre,cur.next = pre;pre的头节点指到cur,pre = cur;cur指向原来的下一个,cur = tmp

【code】

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        dummy = jump = ListNode(-1)
        l = r = dummy.next = head
        while True:
#             找到边界
            while r.next and count <k:
                r = r.next
                count += 1
            if count == k:
                pre,cur = l,r
                for _ in range(k):
                    cur.next, pre, cur = pre, cur, cur.next
#                     tmp = cur.next
#                     cur.next = pre
#                     pre = cur
#                     cur = tmp
#                 jump.next = pre
#                 jump = l
#                 l = r
                jump.next, jump, l = pre,l,r
        return dummy.next

【idea】

先把所有的值放在一个list中,然后按照每k个进行反转。最后将新list中的值生成新的链表。

【code】

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        tmp = []
        res = p = ListNode(0)
        while head and head.next:
            tmp.append(head.val)
            head = head.next
        for i in range(k,len(tmp),k):
            tmp[i: i+k] = tmp[i: i+k][::-1]
        for x in tmp:
            p.next = ListNode(x)
            p = p.next
        return res.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值