实现链表的基本操作(数据结构)-python版

2020-09-21  本文已影响0人  不忘初心_悟空
class Node:
    def __init__(self, data):
        self.data=data
        self.next=None

    def __repr__(self):
        return f"Node(self.data)"


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

    def insert_tail(self,data):
        if self.head is None:
            self.insert_head(data)
        else:
            temp = self.head
            while temp.next:
                temp = temp.next
            temp.next = Node(data)

    def insert_head(self, data):
        new_node = Node(data)
        if self.head:
            new_node.next = self.head
        self.head = new_node

    def print_list(self):
        temp = self.head
        while temp:
            temp = temp.next

    def delete_head(self):
        temp = self.head
        if self.head:
            self.head = self.head.next
        return temp

    def delete_tail(self):
        temp = self.head
        if self.head:
            if self.head.next is None:
                self.head = None
            else:
                while temp.next.next:
                    temp = temp.next
                temp.next, temp = None, temp.next
        return temp

    def is_empty(self):
        return self.head is None

    def reverse(self):
        prev = None
        current = self.head

        while current:
            next_node = current.next

            current.next = prev

            prev = current

            current = next_node

        self.head = prev

    def __repr__(self):
        current =self.head
        string_repr = ""
        while current:
            string_repr += f"{current} -->"
            current = current.next
        return string_repr + "End"

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

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

        for _ in range(index):
            if current.next is Node:
                raise IndexError("Index out of range")
            current = current.next
        return current

    def __setitem__(self, index, data):
        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.data = data

    def __len__(self):

        if not self.head:
            return 0

        count = 0
        cur_node = self.head
        while cur_node.next:
            count += 1
            cur_node = cur_node.next
        return count + 1
上一篇下一篇

猜你喜欢

热点阅读