python学习之链表实现有序表

Posted 今夜月色很美

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之链表实现有序表相关的知识,希望对你有一定的参考价值。

1.定义链表节点对象node

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

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

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

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

2.使用链表实现有序表

from node import Node

class OrderArray:
    def __init__(self):
        self.head = self.last = Node(None)

    def add(self, data):
        currentNode = self.head.getNext()
        previous = self.head
        while currentNode != None:
            if currentNode.getData() > data:
                newNode = Node(data)
                newNode.setNext(currentNode)
                previous.setNext(newNode)
                break
            else:
                previous = currentNode
                currentNode = currentNode.getNext()
        else:
            self.head.setNext(Node(data))

    def removeHead(self):
        firstNode = self.head.getNext()
        if firstNode == None:
            print("有序表已经空了")
            return None
        self.head.setNext(firstNode.getNext())
        return firstNode.getData()

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

3.测试

from order_array import OrderArray

orderArray = OrderArray()
orderArray.add(345)
orderArray.add(6)
orderArray.add(23)
orderArray.add(234)
orderArray.add(45)
print(orderArray.size())
print(orderArray.removeHead())
print(orderArray.removeHead())
print(orderArray.removeHead())
print(orderArray.removeHead())
print(orderArray.removeHead())
print(orderArray.removeHead())
print(orderArray.removeHead())

以上是关于python学习之链表实现有序表的主要内容,如果未能解决你的问题,请参考以下文章

python学习之双端队列和链表实现队列

数据结构和算法学编程必知必会的50个代码实现,你都会了吗?

Python学习之list有序集合

Python数据结构学习笔记——链表:无序链表和有序链表

线性表练习之Example009-求两个有序递增链表的差集

LeetCode第109题—将有序链表转换为二叉搜索树—Python实现