代码随想录算法训练营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
相关推荐
我搞slam18 分钟前
快乐数--leetcode
算法·leetcode·哈希算法
WWZZ20251 小时前
快速上手大模型:机器学习3(多元线性回归及梯度、向量化、正规方程)
人工智能·算法·机器学习·机器人·slam·具身感知
应用市场2 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑2 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
西阳未落2 小时前
LeetCode——二分(进阶)
算法·leetcode·职场和发展
通信小呆呆2 小时前
以矩阵视角统一理解:外积、Kronecker 积与 Khatri–Rao 积(含MATLAB可视化)
线性代数·算法·matlab·矩阵·信号处理
Dfreedom.3 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生3 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
CoderCodingNo3 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
一个不知名程序员www3 小时前
算法学习入门---双指针(C++)
c++·算法