单链表的创建---弦之森

class Node(object):
    """单节点的创建"""

    def __init__(self, elem):
        # item存储数据结构
        self.elem = elem
        # 下一个节点的创建
        self.next = None


class SingleLinkList(object):
    """单链表,对象方法"""

    def __init__(self, node=None):
        self.__head = node

    # 判断链表是否为空:不需要参数
    # @property
    def is_empty(self):
        return self.__head is None

    # 返回链表长度:不需要参数
    def length(self):
        # cur表示游标,用来遍历节点
        cur = self.__head
        # count记录数据
        count = 0
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    # 遍历整个链表:不需要参数
    def travel(self):
        cur = self.__head
        while cur is not None:
            print(f"{cur.elem}、", end='')
            cur = cur.next
        print()

    # 在链表头部添加元素:需要传入参数(节点)
    def add(self, item):
        """头部"""
        node = Node(item)
        node.next = self.__head
        self.__head = node

    # 在链表尾部添加元素:需要传入参数(节点)
    def append(self, item):
        node = Node(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):
        # 将pre指向第一个节点,其下标为0
        node = Node(item)
        # 当用户输入的位置小于0时,提示用户输入大于等于0的数字:
        # if pos < 0:
        #     print("Please input number is big or amount as 0")
        if pos < 0:
            print("Your input number is small as 0,so we think your want to write things at head。")
            self.add(item)
        else:
            if pos > (self.length() - 1):
                print("Your input number is big as most longest,so we think your want to write things at tail。")
                self.append(item)
            else:
                pre = self.__head
                count = 0
                while count != (pos - 1):
                    count += 1
                    pre = pre.next
                # 当循环推出之后,pre指向pos-1位置
                node.next = pre.next
                pre.next = node

    # 删除节点:需要传入参数(节点)
    def remove(self, item):
        cur = self.__head
        while cur.next is not None:
            if cur.next.elem is item:
                cur.next = cur.next.next
            cur = cur.next

    # 查找节点是否存在:
    def search(self, item):
        cur = self.__head
        while cur is not None:
            if cur.elem == item:
                return True
            else:
                cur = cur.next
        return False


ll = SingleLinkList()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值