Stack, usa deque

Le operazioni minime per uno stack (LIFO, last in first out).
La struttura dati nativa collections.deque può essere utilizzata come uno stack.

OperazioneImplementazione
stack=collections.deque() Uno stack vuoto
z.push(x)Aggiunge x allo stackstack.append(x)Aggiunge a destra
x <– z.pop()Restituisce l’ultimo elemento inserito e lo eliminax=stack.pop()Toglie da destra…
z.is_empty()Lo stack è vuoto?len(stack) == 0

Test 1

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

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([])