数据结构与算法-链表

一、单链表

单向链表的存储结构比较简单,在存储上,它能够用一组任意的存储单元存储线性表的数据元素(这组存储单元可以是连续的,也可以是不连续的)。每个元素包含两个域,其中存储数据元素信息的域称为数据域;存储直接后继存储位置的域称为指针域。指针域中存储的信息称作指针或链。

二、双向链表

双向链表的存储结构相对于单向链表更加复杂。在双向链表中,每个节点中有两个指针域,一个指向直接后继,另一个指向直接前驱,当连接为最后一个连接时,指向空值或者空列表

三、循环链表

循环链表是另一种形式的链式存储结构。其特点是表中最后一个节点的指针域指向头节点,整个链表形成一个环。由此,从表中任意节点出发均可找到表中其他节点

四、单链表实现



# 链节点
class ListNode:
   def __init__(self, val=0, next=None):
       self.val = val  # 表示数据元素的值
       self.next = next  # 表示后继指针


# 链表
class LinkedList:
    def __init__(self):
        self.head = None  # 表示链表头节点

    # 动态生成链节点,并且依次将其连接到链表中
    def create(self, data):
        self.head = ListNode(0)
        cur = self.head
        for i in range(len(data)):
            node = ListNode(data[i])
            cur.next = node
            cur = cur.next

    # 求链表长度
    def getLen(self):
        count = 0
        cur = self.head
        while cur:
            count += 1
            cur = cur.next
        return count

    # 查找元素
    def searchVal(self, val):
        cur = self.head
        while cur:
            if cur.next.val == val:
                return cur
            cur = cur.next
        return None

    # 头插法
    def insertByHead(self, val):
        node = ListNode(val)
        node.next = self.head
        self.head = node

    # 尾插法
    def insertByEnd(self, val):
        node = ListNode(val)
        cur = self.head
        while cur.next:
            cur = cur.next
        cur.next = node

    # 中间插入
    def insertByMiddle(self, index, val):
        count = 0
        cur = self.head
        while cur and count < index - 1:
            count += 1
            cur = cur.next

        node = ListNode(val)
        node.next = cur.next
        cur.next = node

    # 修改元素
    def update(self, index, val):
        cur = self.head
        count = 0
        while cur and count < index - 1:
            count += 1
            cur = cur.next
        cur.val = val
    
    # 头删法
    def deleteByHead(self):
        self.head = self.head.next
    
    # 尾删法
    def deleteByEnd(self):
        cur = self.head
        while cur.next:
            cur = cur.next
        self.cur = None
    
    # 中间删除
    def deleteByMiddle(self, index):
        count = 0
        cur = self.head
        while cur and count < index - 1:
            count += 1
            cur = cur.next
        cur.next = cur.next.next
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z_ForWard

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值