【鏈表】用python實現單向鏈表

from typing import Any, Optional

class Node(object):
    def __init__(self, value: Any, next: Optional["Node"]=None):
        self.value = value
        self.next = next

    def __repr__(self):
        return f"Node({self.value})"


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

    def add_front(self, value):
        # 在前端插入值,head重新指向

        # 情況1:若爲空鏈
        if self.head is None:
            self.head = Node(value)

        # 情況2:若爲非空鏈
        else:
            new_node = Node(value, self.head)
            self.head = new_node

    def add_rear(self, value):
        # 在末端插入值,循環查找最後一個元素

        # 情況1:若爲空鏈
        if self.head is None:
            self.head = Node(value)

        # 情況2:若爲非空鏈
        else:
            current = self.head
            while current.next is not None:
                current = current.next

            current.next = Node(value)

    def __len__(self):
        sum = 0
        current = self.head
        while current:
            sum += 1
            current = current.next
        return sum

    def del_front(self):
        # 刪除鏈首,即head重新指向
        if self.head is None:
            raise ValueError("The linkedlist is null!")
        else:
            self.head = self.head.next

    def del_rear(self):
        # 刪除鏈尾
        if self.head is None:
            raise ValueError("The linkedlist is null!")
        elif self.head.next is None:
            self.head = None
        else:
            current = self.head
            while current.next.next:
                current = current.next

            current.next = None

    def isEmpty(self):
        # 判斷是否爲空
        return self.head is None

    def __repr__(self):

        if self.head is None:
            return "Null LinkedList"

        else:
            node_list = []
            node = self.head
            while node:
                node_list.append(f"Node({node.value})")
                node = node.next
            return '——>'.join(node_list)

    def reverse(self):
        # 鏈表的翻轉
        prev = None
        current = self.head
        while current.next:
            next = current.next
            current.next = prev
            prev = current
            current = next

        current.next = prev
        self.head = current

    def insert(self, index, value):
        # 插入某個鏈
        current = self.head
        new_node = Node(value)

        if index == 0:
            new_node.next = current
            self.head = new_node

        else:
            for i in range(1, index):
                current = current.next
                if current is None:
                    raise IndexError("Index out of range")

            next = current.next
            new_node.next = next
            current.next = new_node

    def __getitem__(self, index):
        current = self.head

        if current is None:
            raise IndexError("The Linked List is empty")

        for i in range(index):
            if current.next is None:
                raise IndexError("Index out of range")

            current = current.next

        return current.value

    def __setitem__(self, index, value):
        current = self.head

        if current is None:
            raise IndexError("The Linked List is empty")

        for i in range(index):
            if current.next is None:
                raise IndexError("Index out of range")

            current = current.next

        current.value = value


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章