【1.棧結構的python實現】
棧,線性數據結構,LIFO後進先出,添加和刪除總是發生在同一側。例如:盤子的堆放和拿取
代碼:
【2.隊列】
隊列,FIFO,先進先出,新添加的在隊尾,移除的一端稱隊首,例如:排隊
分析:python實現中,隊列尾部在列表位置0,首部在列表末尾,意味着,插入操作是O(n),刪除操作是O(1)
代碼:
【3.雙端隊列】
deque,雙端隊列,類似於隊列,有兩個端部,首部和尾部,項在雙端隊列中順序不變。可以決定任意的添加和移除順序,可以
說是棧和隊列的結合,同時擁有棧和隊列的許多特性
分析:從deque首部,也就是列表末尾,添加和刪除項是 O(1);而從尾部,也就是列表位置0處,添加和刪除是 O(n)
代碼:
【有序鏈表】
#創建有序列表 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) |