Python 创建单链表

单链表由多个节点组成。

每一个节点有一个值,和一个指针,指针放的是下一个节点的地址。

具体的关于python创建链表的解释就不过多解释,这里给出代码和方法。

更多解释请看 Python数据结构与算法03——单链表、双链表、单项循环链表_哔哩哔哩_bilibili

这个老师讲的非常清楚

链表实现的方法有

        1.判断是否为空

        2. 获取链表的长度

        3.遍历链表

        4.头插法

        5.尾插法

        6.制定位置后插入节点

        7.查找某一节点

        8.删除某一节点

# -*- coding: utf-8 -*- 
"""
@Name: ListNode.py
@Author: 公仔人
@time: 2023/3/24 下午11:57
"""

# 节点类
class ListNode:
    def __init__(self, value):
        self.value = value
        self.next = None


# 链表类
class SingleLinkedList:
    def __init__(self, node=None):
        self.__head = node

    # 判断链表是否为空
    def is_empty(self, ):
        return True if self.__head is None else False

    # 获取链表的长度
    def length(self):
        cur = self.__head
        count = 0
        if self.is_empty():
            return 0

        while cur is not None:
            count += 1
            cur = cur.next
        return count

    # 遍历链表
    def ergodic(self):
        cur = self.__head
        while cur is not None:
            print(cur.value, end="->")
            cur = cur.next

    # 在头部添加
    def add(self, item):
        node = ListNode(item)
        cur = self.__head
        node.next = cur
        self.__head = node

    # 尾部添加节点
    def append(self, item):
        node = ListNode(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            cur.next = node

    # 插入节点到指定位置
    def insert(self, pos, item):
        node = ListNode(item)
        cur = self.__head
        pre = None
        index = 0
        while index < pos - 1:
            index += 1
            pre = cur
            cur = cur.next
        node.next = cur
        pre.next = node

    # 查找某一节点
    def search(self, item):
        cur = self.__head
        index = 0
        while cur.value != item:
            if cur is None:  # 找不到返回False
                return False
            index += 1
            cur = cur.next
        return index

    # 删除某一节点
    def remove(self, item):
        cur = self.__head
        pre = None
        while cur.value != item:
            pre = cur
            cur = cur.next
        if pre is None:  # 删除的是头节点
            self.__head = cur.next
        else:
            pre.next = cur.next


sll = SingleLinkedList()
print(sll.is_empty())
sll.append(6)
sll.append(3)
sll.add(0)
sll.append(5)
sll.append(1)
sll.append(2)
sll.insert(2, 11)
sll.insert(6, 6)
sll.remove(0)
find_index = sll.search(1)
print('1所在位置索引:', find_index)
print(sll.length())
print(sll.ergodic())

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值