代码随想录算法训练营day4(链表)

华子目录

两两交换链表中的节点

思路

  • 使用虚拟头结点(要操作连续的两个节点,就必须找到其上一个节点),cur指向该节点
  • 在交换之前,先对虚拟节点.next虚拟节点.next.next.next临时记录
  • 如果为偶数个节点,则cur.next==None
  • 如果为奇数个节点,则cur.next.next==None
python 复制代码
# 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]:
        virtualHead = ListNode()
        virtualHead.next = head
        cur = virtualHead
        while cur.next != None and cur.next.next != None:  # 这里得先判断cur.next != None,不然如果cur.next为None的话,那么cur.next.next就空指针溢出了
            temp1 = cur.next
            temp2 = cur.next.next.next
            cur.next = cur.next.next
            cur.next.next = temp1
            cur.next.next.next = temp2
            cur = cur.next.next
        return virtualHead.next

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

思路

  • 删除第N个节点,那么我们当前遍历的指针一定要指向第N个节点前一个节点
  • 使用虚拟头结点left,right双指针,初始时,两个指针都指向虚拟头节点
  • right指针先向后移动N次,之后,双指针一起向后移动,当rightNone时,left刚好指向倒数第N个节点
  • 所以right指针一开始向后移动N+1次,这样left就可以指向被删除节点前一个节点
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        virtualHead = ListNode()
        virtualHead.next = head
        left = right = virtualHead
        while n+1>0:
            right = right.next
            n -= 1
        while right != None:
            right = right.next
            left = left.next
        left.next = left.next.next
        return virtualHead.next

链表相交

思路1

  • 先遍历出AB的各个长度lengthAlengthB
  • 计算出差值temp
  • 最长的从头开始向后遍历temp次
  • 然后curAcurB进行判断,如果相等则返回该节点,如果遍历完了还不相等则返回None
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        curA, curB = headA, headB
        lengthA = lengthB = 0
        while curA:
            lengthA += 1
            curA = curA.next
        while curB:
            lengthB += 1
            curB = curB.next
        if lengthA > lengthB:
            temp = lengthA - lengthB
            curA, curB = headA, headB
            while temp:
                curA = curA.next
                temp -= 1
            while curA:
                if curA == curB:
                    return curA 
                curA = curA.next
                curB = curB.next
            return None
        else:
            temp = lengthB - lengthA
            curA, curB = headA, headB
            while temp:
                curB = curB.next
                temp -= 1
            while curA:
                if curA == curB:
                    return curA 
                curA = curA.next
                curB = curB.next
            return None

思路2

  • 使用集合记录一条链表所有内存地址哈希表
  • 再去遍历另一条链表每遍历一个节点,就判断该节点内存地址在不在集合中
  • 如果就返回该节点不在则返回None
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        curA, curB = headA, headB
        hash1 = set()
        while curA:
            hash1.add(curA)
            curA = curA.next
        while curB:
            if curB in hash1:
                return curB
            curB = curB.next
        return None

环形链表II

思路

  • 使用left,right快慢指针两个指针第一次相遇时一定在环中相遇前left每次移动一个节点right每次移动两个节点
  • left,right再次相遇时,就是入环口
python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        left = right = head
        while right and right.next:  # right不为None,right.next也不为None
            left = left.next
            right = right.next.next
            if left == right:
                left = head
                while left != right:
                    left = left.next
                    right = right.next
                return left
        return None
相关推荐
阿里云大数据AI技术40 分钟前
【跨国数仓迁移最佳实践6】MaxCompute SQL语法及函数功能增强,10万条SQL转写顺利迁移
python·sql
你也向往长安城吗1 小时前
推荐一个三维导航库:three-pathfinding-3d
javascript·算法
杜子不疼.1 小时前
《Python学习之文件操作:从入门到精通》
数据库·python·学习
微小的xx1 小时前
java + html 图片点击文字验证码
java·python·html
百度智能云1 小时前
VectorDB+FastGPT一站式构建:智能知识库与企业级对话系统实战
算法
金色旭光1 小时前
uv 现代化的虚拟环境管理工具
python·python进阶
赞哥哥s2 小时前
Python脚本开发-统计Rte中未连接的Port
python·autosar·rte
Franklin2 小时前
Python界面设计【QT-creator基础编程 - 01】如何让不同分辨率图像自动匹配graphicsView的窗口大小
开发语言·python·qt
waynaqua2 小时前
FastAPI开发AI应用三:添加深度思考功能
python·openai·deepseek
onejason2 小时前
《利用 Python 爬虫获取 Amazon 商品详情实战指南》
前端·后端·python