基本数据结构的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())

【链表分析】



链表分析
isEmptyO(1)
sizeO(n)
add(无序列表)O(1)
add(有序列表)O(n) 
searchO(n)
removeO(n)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值