基本数据结构的python实现

【1.栈结构的python实现】

栈,线性数据结构,LIFO后进先出,添加和删除总是发生在同一侧。例如:盘子的堆放和拿取

代码:


【2.队列】

队列,FIFO,先进先出,新添加的在队尾,移除的一端称队首,例如:排队

分析:python实现中,队列尾部在列表位置0,首部在列表末尾,意味着,插入操作是O(n),删除操作是O(1)

代码:


【3.双端队列】

deque,双端队列,类似于队列,有两个端部,首部和尾部,项在双端队列中顺序不变。可以决定任意的添加和移除顺序,可以

说是栈和队列的结合,同时拥有栈和队列的许多特性

分析:从deque首部,也就是列表末尾,添加和删除项是 O(1);而从尾部,也就是列表位置0处,添加和删除是 O(n)

代码:


【4无序链表的python实现】



【有序链表】

#创建有序列表
class OrderedList:
    def __init__(self):
        self.head=None
    def isEmpty(self):
        return self.head==None
    def size(self):
        current=self.head
        count=0
        while current!=None:
            count=count+1
            current=current.getNext()
        return count
    def search(self,item):
        current=self.head
        found=False
        stop=False
        while current!=None and not found and not stop:
            if current.getData()==item:
                found=True
            elif current.getData()>item:
                stop=True
            else:
                current=current.getNext()
        return found
    def add(self,item):
        current=self.head
        previous=None
        stop=False
        #查找部分
        while current!=None and not stop:
            if current.getData()>item:
                stop=True
            else:
                previous=current
                current=current.getData()
        temp=Node(item)
        if previous==None:
            self.setNext(self.head)
            self.head=temp
        else:
            temp.setNext(current)
            previous.setNext(temp)
    def remove(self,data):
        current=self.head
        previous=None
        found=False
        while not found:
            if current.getData==data:
                found=True
            else:
                #先后顺序很重要
                previous=current
                current=current.getNext()
        #在第一个节点处发现
        if previous==None:
            self.head=current.getNext()
        #其他节点处发现
        else:
            previous.setNext(current.getNext())

【链表分析】



链表分析
isEmpty O(1)
size O(n)
add(无序列表) O(1)
add(有序列表) O(n)  
search O(n)
remove O(n)



猜你喜欢

转载自blog.csdn.net/brave_jcc/article/details/79587135