1. 一個列表實作兩個棧
class Twostacks(object): def __init__(self): self.stack=[] self.a_size=0 self.b_size=0 self.top=0 def a_isEmpty(self): return self.a_size==0 def a_push(self,item): self.stack.insert(self.a_size,item) self.a_size+=1 def a_pop(self): if self.a_size>=1: item=self.stack[self.a_size-1] self.stack.remove(item) self.a_size-=1 return item def b_isEmpty(self): return self.b_size==0 def b_push(self,item): self.stack.insert(self.a_size,item) self.b_size+=1 def b_pop(self): if self.b_size>=1: item=self.stack[self.a_size] self.stack.remove(item) self.b_size-=1 return item
2. 兩個棧實作一個佇列
有兩個棧s1,s2。入隊時,將元素壓入s1。出隊時,判斷s2是否為空,如不為空,則直接彈出頂元素;如為空,則將s1的元素逐一「倒入」s2,把最後一個元素彈出並出隊。
class Stack(object): def __init__(self): self.stack=[] def isEmpty(self): return self.stack==[] def push(self,item): self.stack.append(item) def pop(self): if self.isEmpty(): raise IndexError,'pop from empty stack' return self.stack.pop() def size(self): return len(self.stack) class Queue_with_stacks(object): def __init__(self): self.stackA=Stack() self.stackB=Stack() def isEmpty(self): return self.stackA.isEmpty() and self.stackB.isEmpty() def enqueue(self,item): self.stackA.push(item) def dequeue(self): if self.stackB.isEmpty(): if self.stackA.isEmpty(): raise IndexError,'queue is empty.' while self.stackA.size()>=2: self.stackB.push(self.stackA.pop()) return self.stackA.pop() else: return self.stackB.pop()
3. 兩個佇列實作一個棧
class Queue(object): def __init__(self): self.queue=[] def isEmpty(self): return self.queue==[] def enqueue(self,x): self.queue.append(x) def dequeue(self): if self.queue: a=self.queue[0] self.queue.remove(a) return a else: raise IndexError,'queue is empty' def size(self): return len(self.queue) class Stack_with_queues(object): def __init__(self): self.queueA=Queue() self.queueB=Queue() def isEmpty(self): return self.queueA.isEmpty() and self.queueB.isEmpty() def push(self,item): if self.queueB.isEmpty(): self.queueA.enqueue(item) else: self.queueB.enqueue(item) def pop(self): if self.isEmpty(): raise IndexError,'stack is empty' elif self.queueB.isEmpty(): while not self.queueA.isEmpty(): cur=self.queueA.dequeue() if self.queueA.isEmpty(): return cur self.queueB.enqueue(cur) else: while not self.queueB.isEmpty(): cur=self.queueB.dequeue() if self.queueB.isEmpty(): return cur self.queueA.enqueue(cur)
以上就是Python資料結構-堆疊、佇列的實作(二)的內容,更多相關文章請關注PHP中文網(m.sbmmt.com)!