python链表及常见操作

本文阅读 1 分钟
首页 › 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.next = newdata

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


temp = Node(93)
temp.setData(10)
print(temp.getNext())

# 定义一个无序链表
class UnorderedList:
    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.head == None

    def add(self, item):
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count += 1
            current = current.getNext()
        return count

    def search(self, item):
        current = self.head
        found = False
        while current != None and not found:
            if current.getData() == item:
                found = True
            else:
                current = current.getNext()
        return found

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

        if previous == None:
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

myList = UnorderedList()
myList.add(31)
myList.add(77)
myList.add(17)
myList.add(93)
myList.add(26)
myList.add(54)
print(myList.search(17))
myList.remove(54)
print(myList.search(54))
有效的算法设计
« 上一篇 01-21
python平衡查找树AVL
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    5298 篇
  • 评论总数:
    53894 条
  • 标签总数:
    6607 个
  • 总浏览量:
    37577663 次
  • 最后更新:
    昨天 09:44

最多点赞

随便看看

标签TAG