Skip to content

LinkedList

定义

操作

实现

from __future__ import annotations
from typing import Any


class Node:
    def __init__(self, data: Any, next_node: Node = None):
        self.data = data
        self.next = next_node


class LinkedList:
    def __init__(self, head=None):
        self.head = head

    def append(self, data: Any) -> None:
        new_node = Node(data)

        # 空链表
        if self.head is None:
            self.head = new_node

        # 遍历
        current_node = self.head
        while current_node.next is not None:
            current_node = current_node.next
        current_node.next = new_node

    def insert(self, data: Any) -> None:
        new_node = Node(data)

        new_node.next = self.head
        self.head = new_node

    def remove(self, data: Any):

        current_node = self.head

        # 命中头部
        if current_node and current_node.data == data:
            self.head = current_node.next
            return

        # 继续遍历
        previous_node = None
        while current_node and current_node.data != data:
            previous_node = current_node
            current_node = current_node.next

        # 判断是否到尾
        if current_node is None:
            return

        # 命中
        previous_node.next = current_node.next

    def print(self) -> None:

        # 遍历输出
        current_node = self.head
        while current_node:
            print(current_node.data)
            current_node = current_node.next


if __name__ == '__main__':
    ll = LinkedList()

    ll.insert('hello')
    ll.insert('world')
    ll.insert('!')
    ll.print()

    print('###################')
    ll.remove('world')
    ll.print()