def test_push(self): stack = Stack() to_push = 33 stack.push(to_push) self.assertEqual(len(stack), 1) self.assertEqual(stack.peek(), to_push) to_push = "thirty three" stack.push(to_push) self.assertEqual(len(stack), 2) self.assertEqual(stack.peek(), to_push)
def sort_stack(s): sort = Stack() while not s.is_empty(): top_node = s.pop() if sort.is_empty() or sort.peek().val >= top_node.val: sort.push(top_node.val) else: while (not sort.is_empty()) and sort.peek().val < top_node.val: n = sort.pop() s.push(n.val) sort.push(top_node.val) s.head = sort.head s.tail = sort.tail
class MyQueue(object): def __init__(self): self.s1 = Stack() self.s2 = Stack() def enqueue(self, data): self.s1.push(data) def dequeue(self): if self.s2.length > 0: return self.s2.pop() while self.s1.length > 0: self.s2.push(self.s1.pop()) return self.s2.pop() def peek(self): if self.s2.peek() is None: while self.s1.length > 0: self.s2.push(self.s1.pop()) return self.s2.peek() def getLength(self): return self.s1.length + self.s2.length
def sortStack(stackSize=10): s = Stack() print("Before sort") for _ in range(stackSize): data = random.randint(1, stackSize * 10) print(data, end=', ') s.push(data) r = Stack() while not s.isEmpty(): data = s.pop() while (not r.isEmpty() and data > r.peek()): s.push(r.pop()) r.push(data) print("\nPost sort") while not r.isEmpty(): print(r.pop(), end=', ')
def towerOfHanoi(discCount=2): a = Stack() b = Stack() c = Stack() for i in range(discCount, 0, -1): a.push(i) print("Tower A at start") for i in range(1, discCount + 1): print(i) minMoves = 2**discCount - 1 for i in range(minMoves): if i % 3 == 0: if c.length > 0 and a.length > 0: if a.peek() < c.peek(): c.push(a.pop()) else: a.push(c.pop()) elif c.length > 0: a.push(c.pop()) elif a.length > 0: c.push(a.pop()) elif i % 3 == 1: if a.length > 0 and b.length > 0: if a.peek() < b.peek(): b.push(a.pop()) else: a.push(b.pop()) elif a.length > 0: b.push(a.pop()) elif b.length > 0: a.push(b.pop()) elif i % 3 == 2: if b.length > 0 and c.length > 0: if b.peek() < c.peek(): c.push(b.pop()) else: b.push(c.pop()) elif b.length > 0: c.push(b.pop()) elif c.length > 0: b.push(c.pop()) if discCount % 2 == 0: b, c = c, b if a.length > 0: print("Tower A at end") while a.length > 0: print(a.pop()) if b.length > 0: print("Tower B at end") while b.length > 0: print(b.pop()) if c.length > 0: print("Tower C at end") while c.length > 0: print(c.pop()) return