数据结构-链表(二)

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
        
相关推荐
weixin_307779136 分钟前
最小曲面问题的欧拉-拉格朗日方程 / 曲面极值问题的变分法推导
算法
RTC老炮19 分钟前
webrtc弱网-AlrDetector类源码分析与算法原理
服务器·网络·算法·php·webrtc
孤廖25 分钟前
【算法磨剑:用 C++ 思考的艺术・Dijkstra 实战】弱化版 vs 标准版模板,洛谷 P3371/P4779 双题精讲
java·开发语言·c++·程序人生·算法·贪心算法·启发式算法
sali-tec30 分钟前
C# 基于halcon的视觉工作流-章33-矩状测量
开发语言·人工智能·算法·计算机视觉·c#
凯子坚持 c35 分钟前
Redis 核心数据结构:String 类型深度解析与 C++ 实战
数据结构·c++·redis
songx_991 小时前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
于樱花森上飞舞1 小时前
【java】常见排序算法详解
java·算法·排序算法
GawynKing1 小时前
图论3 图的遍历
算法·深度优先
东方芷兰3 小时前
Leetcode 刷题记录 21 —— 技巧
java·算法·leetcode·职场和发展·github·idea
kyle~3 小时前
排序---选择排序(Selection Sort)
java·算法·排序算法