代码随想录算法训练营Day4|链表2|链表操作

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

【中等题】【题目链接

  • 虚拟节点和while判断
  • 总共涉及四个节点,画图看步骤比较清晰
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(next=head)
        current = dummy
        while current.next and current.next.next:
            temp1 = current.next
            temp2 = current.next.next.next
            current.next = current.next.next
            current.next.next = temp1
            current.next.next.next = temp2
            current= current.next.next
        return dummy.next

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

【中等题】【题目链接

  • dummy虚拟头节点
  • 思路一:简单办法,先遍历一次得到总个数,再第N-n个节点
  • 思路二:双指针,快指针比慢指针多走n个,当快指针走到末尾,慢指针指向倒数第n个
#思路一
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        size = 0
        cur = head
        while(cur):
            cur = cur.next
            size += 1
        dummy = ListNode(next = head)
        cur = dummy
        for i in range(size-n):
            cur = cur.next
        cur.next = cur.next.next
        return dummy.next
#思路二
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(next = head)
        fast,slow = dummy,dummy
        for i in range(n):
            fast = fast.next
        while fast.next:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return dummy.next

160.相交链表

【简单题】【题目链接

  • 节点相等=节点地址相等(=定义的类相等?)
  • 思路很巧妙,跟删除倒数第n个值有点类似,也是先走n个数,然后往后遍历是否相等,相对于暴力解法的O(mn),这个复杂度只需要O(m+n)
class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        len1,len2 = 0,0 
        cur = headA
        while(cur):
            len1 += 1
            cur =  cur.next
        cur = headB
        while(cur):
            len2 += 1
            cur = cur.next
        n = min(len1,len2)
        curA,curB = headA,headB
        for i in range(len1-n):
            curA = curA.next
        for i in range(len2-n):
            curB = curB.next
        while(curA!=curB and curA):
            curA = curA.next
            curB = curB.next
        return curA

142.环形链表Ⅱ

【简单题】【题目链接

  • 双指针,快指针速度是慢指针的两倍。检测环+环的入口一气呵成
class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        fast,slow = head,head
        while(fast and fast.next): ## 这里的循环条件注意一下
            fast = fast.next.next
            slow = slow.next   ## 判断是否有环
            if slow == fast:
                slow = head
                while(slow!=fast):
                    slow = slow.next
                    fast = fast.next
                return fast
        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值