数据结构-链表(二)

1.两两交换列表中的节点

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

复制代码
输入:head = [1,2,3,4]
输出:[2,1,4,3]
python 复制代码
class ListNode:
     def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def swapPairs(self, head):
        dummy_node=ListNode(next=head)
        cur=dummy_node
        while cur.next!=None and cur.next.next!=None:
            temp=cur.next
            temp1=cur.next.next.next
            cur.next=cur.next.next
            cur.next.next=temp
            temp.next=temp1
            cur=cur.next.next
        return dummy_node.next
            
                

2.删除链表的倒数第N个数

给你一个链表,删除链表的倒数第 n个结点,并且返回链表的头结点。

复制代码
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
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(head,n):
       dummy_node=ListNode(next=next)
       fast=low=dummy_node
       for i in range(n+1):
            fast=fast.next
       while fast:
            fast=fast.next
            low=low.next
       low.next=low.next.next
       return dummy_node.next

3.链表相交

给你两个单链表的头节点 headAheadB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null

图示两个链表在节点 c1 开始相交**:**

复制代码
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
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:
        lenA,lenB=0,0
        cur=headA
        while cur:
            cur=cur.next
            lenA+=1
        cur=headB
        while cur:
            cur = cur.next
            lenB+=1
        curA,curB=headA,headB
        if lenA > lenB:
            curA,curB=curB,curA
            lenA,lenB=lenB,lenA
        for i in range(lenB-lenA):
            curB=curB.next
        while curA:
            if curA==curB:
                return curA
            else:
                curA=curA.next
                curB=curB.next
        return None
        
相关推荐
reyas31 分钟前
B树系列解析
数据结构·b树
Indigo_code1 小时前
【数据结构】【顺序表算法】 删除特定值
数据结构·算法
阿史大杯茶2 小时前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法
LluckyYH2 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
转调2 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
不穿格子衬衫3 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
wdxylb3 小时前
使用C++的OpenSSL 库实现 AES 加密和解密文件
开发语言·c++·算法
aqua35357423583 小时前
蓝桥杯-财务管理
java·c语言·数据结构·算法
CV金科3 小时前
蓝桥杯—STM32G431RBT6(IIC通信--EEPROM(AT24C02)存储器进行通信)
stm32·单片机·嵌入式硬件·算法·蓝桥杯
sewinger3 小时前
区间合并算法详解
算法