堆栈:
数组实现堆栈的代码:
class ArrayStack(object): def __init__ (self): self._data = [] def __len__ (self): return len(self._data) def is_empty(self): return len(self._data) == 0 # O(1) def push(self, e): self._data.append(e) # O(1) def top(self): if self.is_empty( ): raise ValueError( 'Stack is empty' ) return self._data[-1] # O(1) def pop(self): if self.is_empty( ): raise ValueError( 'Stack is empty' ) return self._data.pop( ) def printstack(self): for i in range(len(self._data)): print(self._data[i], end = ' ') print()
队列实现堆栈的代码:
class LinkedStack(object): def __init__ (self): self._list = LinkedList() def __len__ (self): return self._list.length def is_empty(self): return self._list.length == 0 # O(1) def push(self, e): self._list.add_first(e); # O(1) def top(self): return self._list.get_first().value; # O(1) def pop(self): return self._list.remove_first().value; def printstack(self): self._list.printlist()
队列:
循环数组实现一个队列代码:
class ArrayQueue: DEFAULT_CAPACITY = 10 def __init__(self): self._data = [None] * ArrayQueue.DEFAULT_CAPACITY self._size = 0 self._front = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def first(self): if self.is_empty( ): raise ValueError( 'Queue is empty' ) return self._data[self._front] def dequeue(self): if self.is_empty( ): raise ValueError( 'Queue is empty' ) answer = self._data[self._front] self._data[self._front] = None self._front = (self._front + 1) % len(self._data) self._size -= 1 return answer def enqueue(self, e): if self._size == len(self._data): self._resize(2 * len(self._data)) pos = (self._front + self._size) % len(self._data) self._data[pos] = e self._size += 1 def resize(self, cap): old = self._data self._data = [None] * cap walk = self._front for k in range(self._size): self._data[k] = old[walk] walk = (1 + walk) % len(old) self._front = 0 def printqueue(self): for i in range(self._size): pos = (self._front + self._size - 1 - i) % len(self._data) #print(str(i), ": ", str(pos)) print(self._data[pos], end = " ") print()
用链表去实现队列:
class LinkedQueue(object): def __init__(self): self.head = None self.tail = None self.count = 0 def enqueue(self, value): new_node = Node(value) if self.tail is not None: self.tail.next = new_node else: self.head = new_node self.tail = new_node self.count += 1 def dequeue(self): if not self.is_empty(): # point head to next node tmp = self.head self.head = self.head.next print("dequeue sucess") self.count -= 1 return tmp else: raise ValueError("Empty QUEUE") def is_empty(self): if self.head is None and self.tail is None: return True else: return False def peek(self): return self.head.data def __len__(self): return self.count def is_empty(self): return self.count == 0 def print(self): node = self.head while node: print(node.value, end = " ") node = node.next print('')
练习1:用两个堆栈实现队列
class QueueWithTwoStacks: def __init__(self): self.insertStack = [] self.popStack = [] def enqueue(self, e): self.insertStack.append(e) return e def dequeue(self): if len(self.insertStack) == 0 and len(self.popStack) == 0: return None if len(self.popStack) == 0: while len(self.insertStack) != 0: self.popStack.append(self.insertStack.pop()) return self.popStack.pop() mystack = QueueWithTwoStacks() e = mystack.enqueue(3) print(e) e = mystack.enqueue(2) e = mystack.enqueue(1) print(e)
练习2:用队列实现堆栈
class StackWithQueue: def __init__(self): self.queue = LinkedList() # Push element x onto stack. def push(self, x): self.queue.add_last(x) # Removes the element on top of the stack. def pop(self): size = self.queue.size() for i in range(1, size): self.queue.add_last(self.queue.remove_first()) self.queue.remove_first() def top(self): size = self.queue.size() for i in range(1, size): self.queue.add_last(self.queue.remove_first()) result = self.queue.remove_first() self.queue.add_last(result) return result
练习3:最小栈
import sys from ArrayStack import ArrayStack class MinStack(ArrayStack): def __init__(self): super(MinStack, self).__init__() def push(self, v): newMin = min(v, self.min()) super(MinStack, self).push(NodeWithMin(v, newMin)) def min(self): if (super(MinStack, self).is_empty()): return sys.maxsize else: return super(MinStack, self).top()._min; class NodeWithMin: def __init__(self, v, min): self._value = v self._min = min
练习4:用一个数组堆两个栈
class twoStacks: def __init__(self, n): self.size = n self.arr = [None] * n self.top1 = -1 self.top2 = self.size # Method to push an element x to stack1 def push1(self, x): # There is at least one empty space for new element if self.top1 < self.top2 - 1 : self.top1 = self.top1 + 1 self.arr[self.top1] = x else: print("Stack Overflow ") # Method to push an element x to stack2 def push2(self, x): # There is at least one empty space for new element if self.top1 < self.top2 - 1: self.top2 = self.top2 - 1 self.arr[self.top2] = x else : print("Stack Overflow ") # Method to pop an element from first stack def pop1(self): if self.top1 >= 0: x = self.arr[self.top1] self.top1 = self.top1 -1 return x else: print("Stack Underflow ") # Method to pop an element from second stack def pop2(self): if self.top2 < self.size: x = self.arr[self.top2] self.top2 = self.top2 + 1 return x else: print("Stack Underflow ")
练习5:堆栈排序
def sortStack(s): r = ArrayStack() while not s.is_empty(): tmp = s.pop() while not r.is_empty() and r.top() > tmp: s.push(r.pop()) r.push(tmp) return r
练习6:字符串反转
def reverse(s): lst = [] for i in s: lst.append(i) result = [] while len(lst) != 0: result.append(lst.pop()) return ''.join(result)
练习7:回文字符串
def IsPalindrome(s): r = reverse(s) return r == s