Classe
La nuovo struttura dati utilizza una lista (list)
class Stack: def __init__(self): self._lista=[] def push(self, x): self._lista.append(x) def pop(self): return self._lista.pop() def is_empty(self): return (len(self._lista) == 0)
Test 1
stack=Stack() # [] stack.push(18) # [18] stack.push(1) # [18, 1] stack.push(28) # [18, 1, 28] print(stack.is_empty()) # False print(stack.pop()) # [18, 1] 28 print(stack.is_empty()) # False print(stack.pop()) # [18] 1 print(stack.is_empty()) # False print(stack.pop()) # [] 18 print(stack.is_empty()) # True
Test 2
stack=Stack() # [] for x in range(5): stack.push(x) print(stack._lista) # [0, 1, 2, 3, 4] while(not stack.empty()): print(stack.pop(), end=" ") # 4 3 2 1 0 print() print(stack._lista) # []
Continua…
- x <– top(), l’elemento in cima allo stack
- n <– size(), quanti elementi contiene?