python 数据结构之 单向链表 的定义以及类函数的定义

这篇博客详细介绍了如何使用Python定义一个单向链表的数据结构,包括节点类和链表类的定义,实现了添加、搜索、插入、删除、获取指定索引节点等操作,以及迭代器和字符串表示的方法。代码示例展示了链表的创建和操作,如添加元素、插入元素、遍历链表等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 数据结构之 单向链表 的定义以及类函数的定义:
在这里插入图片描述

class Node(object):   # 定义节点类: 单个节点
    """
    An object for storing a single node in a linked list
    Attributes:
        data: Data stored in node
        next: Reference to next node in linked list
    """
    def __init__(self, data_in, next_in = None):
        self.data = data_in
        self.next = next_in

    def __repr__(self):
        return str(self.data)

class SinglyLinkedList(object):
    """
    Linear data structure that stores values in nodes. The list maintains a reference to
    the first node, also called head. Each node points to the next node in the list
    Attributes:
        head_node: The head node of the list
    """
    def __init__(self):
        self.head_node = None
        # Maintaining a count attribute allows for len() to be implemented in
        # constant time
        self.__count = 0

    def is_empty(self):
        """
        Determines if the linked list is empty
        Takes O(1) time
        """
        return self.head_node is None

    def __len__(self):
        """
        Returns the length of the linked list
        Takesn O(1) time
        """
        return self.__count

    def add(self, data):
        """
        Adds new Node containing data to head_node of the list
        Also called prepend
        Takes O(1) time
        """
        new_node = Node(data, next_in =self.head_node)
        self.head_node = new_node
        self.__count += 1

    def search(self, key):
        """
        Search for the first node containing data that matches the key
        Returns the node or `None` if not found
        Takes O(n) time
        """
        curr_node = self.head_node

        while curr_node:
            if curr_node.data == key:
                return curr_node
            else:
                curr_node = curr_node.next
        return None

    def insert(self, data, index):
        """
        Inserts a new Node containing data at index position
        Insertion takes O(1) time but finding node at insertion point takes
        O(n) time.
        Takes overall O(n) time.
        """
        if index >= self.__count:
            raise IndexError('index out of range')
        if index == 0:
            self.add(data)
            return
        if index > 0:
            new = Node(data)
            curr_node = self.head_node
            """
            position = index

            while position > 1:
                curr_node = curr_node.next
                position -= 1
            """
            while index-1:
                curr_node = curr_node.next
                index -= 1

            prev_node = curr_node
            next_node = curr_node.next

            prev_node.next = new
            new.next = next_node

        self.__count += 1

    def node_at_index(self, index):
        """
        Returns the Node at specified index
        Takes O(n) time
        """

        if index >= self.__count:
            raise IndexError('index out of range')

        if index == 0:
            return self.head_node

        current = self.head_node
        position = 0

        while position < index:
            current = current.next
            position += 1

        return current

    def remove(self, key):
        """
        Removes Node containing data that matches the key
        Returns the node or `None` if key doesn't exist
        Takes O(n) time
        """

        current = self.head_node
        previous = None
        found = False

        while current and not found:
            if current.data == key and current is self.head_node:
                found = True
                self.head_node = current.next
                self.__count -= 1
                return current
            elif current.data == key:
                found = True
                previous.next_node = current.next
                self.__count -= 1
                return current
            else:
                previous = current
                current = current.next

        return None

    def remove_at_index(self, index):
        """
        Removes Node at specified index
        Takes O(n) time
        """

        if index >= self.__count:
            raise IndexError('index out of range')

        current = self.head_node

        if index == 0:
            self.head_node = current.next
            self.__count -= 1
            return current

        position = index

        while position > 1:
            current = current.next
            position -= 1

        prev_node = current
        current = current.next
        next_node = current.next

        prev_node.next = next_node
        self.__count -= 1

        return current

    def __iter__(self):
        curr_node = self.head_node
        while curr_node:
            yield curr_node
            curr_node = curr_node.next

    def __repr__(self):
        """
        Return a string representation of the list.
        Takes O(n) time.
        """
        nodes = []
        curr_node = self.head_node
        while curr_node:
            if curr_node is self.head_node:
                nodes.append("[Head: %s]" % curr_node.data)
            elif curr_node.next is None:
                nodes.append("[Tail: %s]" % curr_node.data)
            else:
                nodes.append("[%s]" % curr_node.data)
            curr_node = curr_node.next

        return  ' -> '.join(nodes)


if __name__ == '__main__':
    N1 = Node(12)
    N2 = Node(22)
    # print(N1)

    ll1 = SinglyLinkedList()
    ll1.add(13)
    ll1.add(23)
    ll1.add(33)
    ll1.add(43)
    ll1.add(N1)
    ll1.add(N2)

    print(len(ll1))
    ll1.insert(100, 1)
    print(ll1)

    for i in ll1:   #     def __iter__(self): 赋予了 类实例的可迭代特性
        print(i)

运行结果:

6
[Head: 22] -> [100] -> [12] -> [43] -> [33] -> [23] -> [Tail: 13]
22
100
12
43
33
23
13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值