READING-NOTE

View on GitHub

Stacks_and_Queues

Stack

Queue

FIFO & LILO and LIFO & FILO Principles

Queue: First In First Out (FIFO): The first object into a queue is the first object to leave the queue, used by a queue.

Stack: Last In First Out (LIFO): The last object into a stack is the first object to leave the stack, used by a stack

OR

Stack: Last In First Out (FILO): The First object or item in a stack is the last object or item to leave the stack.

Queue: Last In First Out (LILO): The last object or item in a queue is the last object or item to leave the queue.

stacks Code


# Python program to
# demonstrate stack implementation
# using collections.deque
 
 
from Collections import deque
 
stack = deque()
 
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
 
print('Initial stack:')
print(stack)
 
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
 
print('\nStack after elements are popped:')
print(stack)
 
# uncommenting print(stack.pop()) 
# will cause an IndexError
# as the stack is now empty

# // Output: _________________________________

# Initial stack:
deque(['a', 'b', 'c'])

# Elements popped from stack:
c
b
a

# Stack after elements are popped:
deque([])

Queue Code

# Python program to
# demonstrate queue implementation
# using collections.dequeue
 
 
from collections import deque
 
# Initializing a queue
q = deque()
 
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
 
print("Initial queue")
print(q)
 
# Removing elements from a queue
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
 
print("\nQueue after removing elements")
print(q)
 
# Uncommenting q.popleft()
# will raise an IndexError
# as queue is now empty
# Output: ______________________________
 

# Initial queue
deque(['a', 'b', 'c'])

# Elements dequeued from the queue
a
b
c

# Queue after removing elements
deque([])