数据结构-链表(二)

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
        
相关推荐
mmmmath_31 分钟前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil2086 分钟前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z10 分钟前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode
码少女20 分钟前
数据结构——堆排序
数据结构
神仙别闹10 小时前
基于 C++ 实现两个有序链表序列的交集
java·c++·链表
政企项目老覃11 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水12 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR12 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵12 小时前
MATLAB-matlab基础知识
学习·算法·matlab