算法通关村第二关黄金挑战——k个一组链表反转

k个一组链表反转

我的思路——穿针引线法

一组一组拎出来反转

缺点:建立了四个指针,这也太多了一点

def reverseKGroup(self, head, k):
    def reverse(head, lastnode):
        #要注意返回的参数必须是两个,所以把lastnode放到了最前面
        lastnode = head
        if not head or not head.next:
            return head,lastnode
        cur = head.next
        head.next = None
        while cur:
            next = cur.next
            cur.next = head
            head = cur
            cur = next
        return head, lastnode

    dummy_head = ListNode(0)
    dummy_head.next = head
    pre = dummy_head
    slow = fast = head
    for i in range(0, k - 1):
        if fast:
            fast = fast.next
        else:
            return head
    while fast:
        last = fast.next
        fast.next = None
        slow, fast = reverse(slow, fast)
        pre.next = slow
        fast.next = last
        while slow != last and fast:
            slow = slow.next
            fast = fast.next
            pre = pre.next
    return dummy_head.next

老师的代码

class ReverseKGroup:
    def reverseKGroup(self,head,k):
        dummy=ListNode(0)
        dummy.next=head

        pre=end=dummy
        while end.next:
            i=0
            while i<k and end:
                end=end.next
                i+=1
            if not end:break

            startNode=pre.next
            nextNode=end.next
            end.next=None

            pre.next=self.reverse(startNode)

            startNode.next=nextNode

            pre=startNode
            end=pre
        return dummy.next

    def reverse(self,head):
        pre=None
        curr=head
        while curr:
            nextNode=curr.next
            curr.next=pre
            pre=curr
            curr=nextNode
        return pre

头插法

很巧妙的想法.

def reverseKGroup(self, head, k):
    dummy=ListNode(0)
    dummy.next=head
    pre=tail=dummy
    while True:
        count=k
        while count and tail:
            count-=1
            tail=tail.next
        if not tail:break
        head=pre.next
        while pre.next!=tail:
            cur=pre.next
            pre.next=cur.next
            cur.next=tail.next
            tail.next=cur
        pre=tail=head
    return dummy.next

回顾白银挑战——指定区间反转,我试了一下头插法代码,也可以很好完成

def reverseBetween(self, head, left, right):
    dummy=ListNode(0)
    dummy.next=head
    pln=rn=dummy
    for i in range(0,left-1):
        pln=pln.next
    for i in range(0,right):
        rn=rn.next
    while pln.next!=rn:
        cur=pln.next
        pln.next=cur.next
        cur.next=rn.next
        rn.next=cur
    return dummy.next

总结

区间类型的反转用头插法,我觉得重点是抓住区间的前的那一个指针pre和区间末尾的指针lastnode,然后把区间内的节点都移到末尾后面去,直到pre.next=lastnode。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值