Python链表的实现

发布时间:2024年01月21日

还有如下功能未有实现:

  1. insert
  2. pop
  3. index
    python中的列表是基于数组实现的

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

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self, newdata):
        self.data = newdata

    def setNext(self, newnext):
        self.next = newnext


# 无序列表
class UnorderedList:
    def __init__(self):
        self.head = None

    def isEmpty(self):
        return not self.head

    def add(self, item):
        """
        分三步走:
        创建一个新的节点
        将现在的头节点设置为下一节点
        将新节点设置为头节点
        :param item:
        :return:
        """
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp

    """
    链表遍历技术
    """
    def length(self):
        count = 0
        current = self.head
        while current:
            count += 1
            current = current.getNext()
        return count

    def search(self, item):
        current = self.head
        while current:
            if current.getData == item:
                return True
            current = current.getNext
        return False

    def remove(self, item):
        current = self.head
        previous = None
        while current:
            if current.getData == item:
                if not previous:
                    self.head = current.getNext
                else:
                    previous.setNext(current.getNext)
            else:
                previous = current
                current = current.getNext

    def append(self, item):
        current = self.head
        while current:
            current = current.getNext
        current.setNext(Node(item))

文章来源:https://blog.csdn.net/weixin_45977617/article/details/135733625
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。