代码随想录跟练打卡Day4

24. 两两交换链表中的节点 

24. 两两交换链表中的节点

解题关键:

需要画图:

当前节点在交换节点之前一个。

需要使用两个临时值来保存数据。1点和3点

def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode(next= head)
        curr = dummy_head
        while curr.next and curr.next.next:
            tem1 = curr.next 
            tem2 = curr.next.next.next

            curr.next =  curr.next.next 
            curr.next.next = tem1 
            tem1.next= tem2
            curr = curr.next.next
        
        return dummy_head.next

 19.删除链表的倒数第N个节点 

解题关键:

快指针比满指针多走n+1 个

当快指针不为空时,慢指针指向next.next

def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy_head = ListNode(next = head)
        fast = slow = dummy_head
        for i in range(n+1):
            fast= fast.next 
        while fast:
            fast = fast.next 
            slow = slow.next 
        slow.next = slow.next.next 
        return dummy_head.next 

 面试题 02.07. 链表相交 

面试题 02.07. 链表相交

解题关键:

1、遍历链表的条件:while 链表还是while链表.next

while后面的条件是结束循环的条件,即不包括这个,如果结束条件是next则少遍历一个。

2、交换链表的时候不要忘记长度也要交换

3、计算完链表长度后记得链表归零

def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        ln_A = headA
        ln_B = headB
        len_A,len_B=0,0
        while ln_A:
            ln_A=ln_A.next 
            len_A+=1
        while ln_B:
            ln_B=ln_B.next 
            len_B+=1
        curr_A,curr_B=headA ,headB
        if len_A>len_B:
            curr_A,curr_B = headB,headA
            len_A,len_B = len_B,len_A
        for i in range(len_B-len_A):
            curr_B=curr_B.next 
        while curr_B:
            if curr_B==curr_A:
                return curr_B 
            else:
                curr_A=curr_A.next
                curr_B=curr_B.next
        return None

 142.环形链表II 

142. 环形链表 II

解题关键:快指针比慢指针多走一步,如果两者能相等,则说明有环,否则没有:

当两者相遇后,让慢指针回到原点,快慢指针再次相遇的位置即为环的起点。

def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast = head 
        slow = head 
        while fast and fast.next:
            fast = fast.next.next 
            slow = slow.next 
            if fast==slow:
                slow = head 
                while fast != slow :
                    slow= slow.next 
                    fast = fast.next 
                return slow 
        return None

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值