The Stack and Queue Module for Python
The storage in computers is organized thanks to data structure, which enables us to retrieve and modify data in an efficient manner. Stacks and queues hold the distinction of being the first data structures ever defined in the field of computer science. A straightforward Python list can perform the duties of both a queue and a stack in addition to that. A queue is a data structure that is used in computer programming for the purpose of sorting data according to the FIFO rule (First In First Out). It is usual practice to create stacks and queues using a linked or array-based structure.
list.
Stack
A data structure known as a stack implements the LIFO (Last In First Out) principle in its operation. To put in place a stack, we will need two straightforward
operations:
-
push –
It adds an element to the top of the stack. -
pop –
It removes an element from the top of the stack.
Methods of operation:
W01A3@@1 Attributes and Qualities:
- Insertion order of the stack is preserved.
- Useful for parsing the operations.
- Duplicacy is allowed.
Code
-
# Code to demonstrate Implementation of
-
# stack using list
-
x = [
“Python”
,
“C”
,
“Android”
]
-
x.push(
“Java”
)
-
x.push(
“C++”
)
-
print
(x)
-
print
(x.pop())
-
print
(x)
-
print
(x.pop())
-
print
(x)
Output:
['Python', 'C', 'Android', 'Java', 'C++'] C++ ['Python', 'C', 'Android', 'Java'] Java ['Python', 'C', 'Android']
Queue
First-in-First-Out, or FIFO, is the principle that governs how a queue works. Due to the fact that it can be opened from either end, we are able to quickly add elements to the back and remove things from the front.
In order to create a queue, we will need two simple things:
operations:
-
enqueue –
It adds an element to the end of the queue. -
dequeue –
It removes the element from the beginning of the queue.
Procedures Performed on the Queue
W01A3@@4 Attributes and Qualities
- Insertion order of the queue is preserved.
- Duplicacy is allowed.
- Useful for parsing CPU task operations.
Code
-
import
queue
-
# Queue is created as an object ‘L’
-
L = queue.Queue(maxsize=
10
)
-
-
# Data is inserted in ‘L’ at the end using put()
-
L.put(
9
)
-
L.put(
6
)
-
L.put(
7
)
-
L.put(
4
)
-
# get() takes data from
-
# from the head
-
# of the Queue
-
print
(L.get())
-
print
(L.get())
-
print
(L.get())
-
print
(L.get())
Output:
9 6 7 4