Stack, usa deque
Le operazioni minime per uno stack (LIFO, last in first out) push(x), aggiunge x allo stack x <– pop(), restituisce l’ultimo elemento inserito e lo elimina is_empty(), lo stack è vuoto? La struttura dati collections.deque può essere utilizzata come uno stack
1 2 3 |
push(x) : stack.append(x) # aggiunge a destra... x <-- pop(): x=stack.pop() # toglie da destra... is_empty() : len(stack) == 0 |
Test 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import collections stack=collections.deque() # Lo stack vuoto stack.append(18) # [18] stack.append(1) # [18, 1] stack.append(28) # [18, 1, 28] print(len(stack) == 0) # False print(stack.pop()) # [18, 1] 28 print(len(stack) == 0) # False print(stack.pop()) # [18] 1 print(len(stack) == 0) # False print(stack.pop()) # [] 18 print(len(stack) == 0) # True |
Test 2
1 2 3 4 5 6 7 8 9 10 |
import collections stack=collections.deque() # deque([]) for x in range(5): stack.append(x) print(stack) # deque([0, 1, 2, 3, 4]) while(len(stack) != 0): print(stack.pop() ) # 4 3 2 1 0 print(stack) # deque([]) |