数据结构-链表(二)

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
        
相关推荐
DevangLic20 分钟前
数据结构-单链表的头插法和尾插法-
数据结构·c++·学习
陈壮实的搬砖日记1 小时前
激活函数为何能增强神经网络的非线性表达能力?
深度学习·算法·机器学习
点云侠1 小时前
PCL 点云旋转的轴角表示法
人工智能·线性代数·算法·计算机视觉·矩阵
君鼎1 小时前
剑指offer37_数组中出现次数超过一半的数字
数据结构·算法
豆沙沙包?2 小时前
2025年- H83-Lc191--139.单词拆分(动态规划)--Java版
java·算法·动态规划
潘小安2 小时前
『算法』图解数组排序全家桶 - 堆排序
算法·react.js·面试
星沁城2 小时前
172. 阶乘后的零
java·算法·leetcode
玉~你还好吗3 小时前
【LeetCode#第198题】打家劫舍(一维dp)
算法·leetcode
G等你下课4 小时前
摆动序列
算法