预备

这是一个完整结构的linked list

class Node:
    def __init__(self, _data, _next = None):
        self.data = _data
        self.next = _next

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

class linked_list:
    def __init__(self, length, head):
        self.length = length
        self.head = head

    def isEmpty(self):
        if not self.length:
            return True

    def append(self, data):
        # a judgement on the type of this data
        if not isinstance(data, Node): # build-in function
            item = Node(data)
        else:
            item = data
        node = self.head

        # a judgement on the head of the linked list
        if not node:
            self.head = item

        else:
            while node.next:
                node = node.next
            node.next = item
            print(item.data)
        self.length +=1

    def delete(self,index):
        # in case that linked list is empty or index is larger than the length of the linked list
        if self.isEmpty() or index > self.length:
            return None

        else:
            # in case the length of linked_list is 1
            if self.length == 1:
                self.head = None
                self.length = 0

            else:
                index -= 2
                last = self.head
                next_node = last.next.next
                while index:
                    last = last.next
                    next_node = next_node.next
                    index -= 1

                print(last.next.data)
                last.next = next_node

                self.length -= 1


    def insert(self,data, index):
        if index > self.length + 1 :
            return None
        else:
            # a judgement on the type of this data
            if not isinstance(data, Node):  # build-in function
                item = Node(data)
            else:
                item = data

            if index == self.length + 1:
                self.append(item)
            else:
                last = self.head
                index -= 2
                while index:
                    index -= 1
                    last = last.next
                item.next = last.next
                last.next = item
            self.length += 1
        
    def clear(self):
        self.length = 0
        self.head = None
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容