1 堆
堆是一种二叉树,其中每个父节点的值都小于或等于其所有子节点的值,最小的元素总是位于二叉树的根节点。
堆的创建
import heapq import random data = range(10) random.shuffle(data) #打乱顺序 heap = [] for n in data: heapq.heappush(heap,n) print heap heapq.heappushpop(heap,0.5) #新数据入堆 heapq.heappop(heap) #弹出最小的元素,堆重建
列表转化为堆
myheap = [100,2,3,4,22,7,10,5] heapq.heapify(myheap) #将列表转化为堆 heapq.heapreplace(myheap,6) #替代堆栈元素值,堆重建 heapq.nlargest(3,myheap) #返回最大的3个值 heapq.nsmallest(3,myheap) #最小3个
2 队列
队列的特点是First in first out, last in last out,先进先出,后进后出
import Queue q = Queue.Queue() q.put(0) #元素入队 q.put(1) q.put(2) print q.queue #deque([0, 1, 2]) print q.get() #元素0先出队 print q.queue() #deque([1, 2])
3 栈
栈的特点是Last in last out,first in last out,后进先出,先进后出
list 就可以实现栈的基本操作,append()相当于入栈,pop()相当于出栈,但是当列表为空时pop()操作会有异常,也无法限制栈的大小。
import Stack x = Stack.Stack() x.push(1) x. push(2) x.show() x.pop() x.show()
class Stack: def __init__(self, size=10): self._content = [] self._size = size def empty(self): self._content = [] def isEmpty(self): if not self._content: return True else: return False def setSize(self,size): self._size = size def isFull(self): if len(self._content)==self._size: return True else: return False def push(self,v): if len(self._content)<self._size: self._content.append(v) else: print ‘Stack Full‘ def pop(self): if self._content: return self._content.pop() else: print ‘Stack is empty!‘ def show(self): print self._content def showRemainderSpace(self): print ‘Stack can still PUSH‘,self.size-len(self._content),‘elements.‘ if __name__==‘__main__‘: print ‘Please use me as a module‘
4 链表
可以直接使用list及其基本操作实现链表的功能
linkTable = [] linkTable.append(3) linkTable.append(5) linkTable.insert(1,4) linkTable.remove(linkTable[1])
5 二叉树
…
6 有向图
…