day4:链表第二天

@day4:链表第二天

链表第二天

Leetcode 24:Swap Nodes in Pairs

错误代码 非常重要

cur=tmp is Shallow Copy with same memory chunk and address!!!

So, changing cur is changing tmp, which will cause Time Limit Exceeded problem

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # split as small task: swap 1>2 as 2>1
        dummynode = ListNode(next=head)
        cur = dummynode
        while cur.next and cur.next.next:
            tmp = cur
            cur.next = tmp.next.next
            cur.next.next = tmp.next
            # link to the next one problem
            cur.next.next.next = tmp.next.next.next
            cur = cur.next.next
            
        return dummynode.next         

Modified Version:

        # split as small task: swap 1>2 as 2>1
        dummynode = ListNode(next=head)
        first = dummynode
        while first.next and first.next.next:
            second = first.next
            third = first.next.next
            forth = first.next.next.next
            first.next = third
            first.next.next = second
            first.next.next.next = forth
            first=first.next.next
            
        return dummynode.next 

Leetcode 19 Remove Nth Node From End of List

尽量别用head, 会随时改变链表, 最好每次都给头节点 dummyhead
(同样的问题)

        cur = ListNode(next=head)
        dummy = cur
        while n>0 and dummy:
            dummy = dummy.next
            n-=1
        dummy = dummy.next
        dummy2 = cur
        while dummy:
            dummy = dummy.next
            dummy2 = dummy2.next
        dummy2.next = dummy2.next.next
        return cur.next

Leetcode 142

快慢指针判断循环

        # first initiate two pointers
        dummy = ListNode(next = head)
        fast = dummy.next #fast
        slow = dummy.next #slow
        # if fast can break--> no cysle; if they have a cycle:--> fast == slow!
        Flag = True
        while Flag:    
            if (not fast) or (not fast.next):
                return  None
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                Flag = False
        fast = dummy.next
        while fast!=slow:
            fast = fast.next
            slow = slow.next
        return fast

总结:整个链表章节不难 注意创建虚拟节点就好!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值