Python数据结构与算法——单链表

什么是单链表

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 相比于线性表顺序结构,操作复杂。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。

单链表的实现


class Node:
    def __init__(self, value):
        self.__data = value
        self.__next = None

    @property
    def data(self):
        return self.__data

    @data.setter
    def data(self, value):
        self.__data = value

    @property
    def next(self):
        return self.__next

    @next.setter
    def next(self, node):
        self.__next = node



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

    def is_empty(self):
        return self.__head == None

    def len(self):
        current = self.__head
        count = 0

        while current is not None:
            count = count + 1
            current = current.next

        return count

    def is_exists(self, item):
        current = self.__head
        found = False

        while current is not None and not found:
            if current.data == item:
                found = True
            else:
                current = current.next

        return found

    def add_front(self, item):
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def add_rear(self, item):
        current = self.__head
        node = Node(item)

        if current is None:
            self.add_front(item)
        else:
            while current.next is not None:
                current = current.next

            current.next = node

    def insert(self, item, pos):
        node = Node(item)

        if pos <= 0:
            self.add_front(item)
        elif pos >= self.len():
            self.add_rear(item)
        else:
            current = self.__head

            for i in range(pos - 1):
                current = current.next

            node.next = current.next
            current.next = node

    def remove_front(self):
        current = self.__head

        if current is None:
            return

        self.__head = current.next

    def remove(self, item):
        current = self.__head
        previous = None
        found = False

        while not found:
            if current.data == item:
                found = True
            else:
                previous = current
                current = current.next

        if previous is None:
            self.remove_front()
        else:
            previous.next = current.next
            

    def walk_through(self):
        current = self.__head

        while current is not None:
            yield current.data
            current = current.next

你可能感兴趣的:(Python数据结构与算法——单链表)