数据结构之链表

链表是一种常见的线性数据结构,它由一系列节点组成,每个节点包含了数据和指向下一个节点的引用。

链表中的元素在内层中不是连续存储的,这使得链表在插入和删除元素时更高效,因为不需要移动其他元素

链表的原理:

  • 节点结构:每个节点包含两个部分,数据域和指针域(数据和指向下一个节点的引用)
  • 头节点:链表的第一个节点
  • 尾节点:链表的最后一个节点,指向下一个节点的引用为None
  • 插入操作:可以在链表的任意位置插入新节点,只需要改变相邻节点的引用
  • 删除操作:可以删除链表的任意位置上的节点,只需要改变要删除的节点的相邻节点的引用
  • 从头节点开始,逐个节点查找,直到找到目标节点或达到链表结尾
python 复制代码
class LinkNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None
        
    def append(self, val):
        """在链表末尾增加节点"""
        new_node = LinkNode(val)#注意:new_node.next = None
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node

    def prepend(self, val):
        """在链表头部添加节点"""
        new_node = LinkNode(val)
        new_node.next = self.head
        self.head = new_node

    def delete(self, val):
        """删除第一个值为val的节点"""
        if not self.head:
            return
        if self.head.val == val:
            self.head = self.head.next

        current = self.head
        while current.next and current.next.val != val:
            current = current.next
        if current.next:
            current.next = current.next.next

    # def insert_after_node(self, prev_node, val):
    #     """在指定节点后插入新节点"""
    #     if not prev_node:
            

    def find(self, val):
        """查找值为val的节点,返回第一个值为val的节点/None"""
        current = self.head
        while current and current.val != val:
            current = current.next
        if current.next:
            return current.next
        return None
    
    def display(self):
        """打印链表内容"""
        elements = []
        current = self.head
        while current:
            elements.append(current.val)
            current = current.next
        print("->".join(map(str, elements)), end='')
        print('->None')

    # def size(self):
    #     """返回链表的长度,即链表元素的个数"""
相关推荐
孟健1 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
HXhlx2 小时前
CART决策树基本原理
算法·机器学习
码路飞3 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
Wect3 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱3 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
曲幽5 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程10 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪10 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook10 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
Gorway10 小时前
解析残差网络 (ResNet)
算法