Stack and Queue
Stack and Queue
Objectives:
At the end of the chapter, the students will be able to:
• In programming, a stack is an abstract, linear data type with a predefined capacity (or
boundary).
• It follows a particular order for adding or removing elements.
• Linear data structures organized their components in a straight line, so if we add or
remove an element, they will grow or shrink respectively.
• Last In First Out (LIFO) or First In Last Out (FILO) - To conceptualized stacks using a stack
of plates placed in a box. The first plate placed in the stack (the plate at the bottom of
the stack) will be the last one to removed, and the plate added last would be the first
to be removed.
• Stacks are used in a variety of ways when we code. We use stacks to implement
functions, parsers, expression evaluation, and some algorithms.
• Stacks are great for processing nested structures, so they are important for
understanding recursion.
• A simple real-world application of a stack is reversing a string letter by letter. Another
good example of a data stack is the undo and redo function on a computer or text
editor. Undo removes your mist recent change, and redo builds upon already existing
changes.
• How do Stacks work?
- The pop method removes or deletes elements from the stack, while
the push method adds items to the stack.
- When an element is inserted into a stack, it takes the top position and the
variable storing this position points to the number below it. The top variable
should be updated anytime an element is inserted or removed from it.
- What’s important to remember is that insertion and deletion happen on the
same end of a Stack.
• Instead of using array, we can also use linked list to implement stack. Linked list
allocates the memory dynamically. However, time complexity in both the scenario is
same for all the operations i.e. push, pop and peek.
• In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory. Each node contains a pointer to its immediate successor node in the stack.
• Stack is said to be overflown if the space left in the memory heap is not enough to
create a node.
• The top most node in the stack always contains null in its address field.
Queue
Types of Queues
• There are three common types of queues you can expect to encounter. So farm we
learned about the Linear Queue. The other two queues are:
1. Circular Queue: In a circular queue, the last element is connected to the first
element to form a circle. Initially, the front and rear parts of the queue point to
the same location, but they move apart as more elements are inserted into the
queue. A real-life example of a circular queue is an automated traffic signal
system.
2. Priority Queue: In priority queues, elements are sorted based on priority. The most
important element appears first, and the least important appears last. Priority
queues are used in operating systems for load balancing to determine which
programs should be given more priority.
• The array implementation cannot be used for the large scale applications where the
queues are implemented. One of the alternatives of array implementation is linked list
implementation of queue.
• In a linked queue, each node of the queue consists of two parts i.e. data part and the
link part. Each element of the queue points to its immediate next element in the
memory.
• In the linked queue, there are two pointers maintained in the memory i.e. front pointer
and rear pointer. The front pointer contains the address of the starting element of the
queue while the rear pointer contains the address of the last element of the queue.
• Insertion and deletions are performed at rear and front end respectively. If front and
rear both are NULL, it indicates that the queue is empty.
• The linked representation of queue:
Stacks Queues
Pros
• It is easy to implement and logical • Queues are flexible.
for beginners. • They can handle multiple data
• It allows you to control how memory types.
is allocated. • Data queues are fast and
• Easier to use than queues. optimized.
Cons
• Neither flexible nor scalable. • Inserting/removing elements from
• Random access to elements in a the middle is complex.
stack is nearly impossible. • Queues are not readily searchable.
- pop(): this method removes an element from the top of the stack and returns it.
- push(): this method adds an element to the top of the stack.
• From there we can apply all sorts of methods for more functionality and information
retrieval:
Stack in Python
Sample Program
Push Stack
class Stack:
def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
OUTPUT
Tue
Thu
Sample Program
POP from a Stack
class Stack:
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
OUTPUT
Thu
Wed
Sample Program
class Queue:
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
OUTPUT
Sample Program
class Queue:
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())
OUTPUT
Mon
Tue
Assessment
I. Code the following output:
1. Remove Saturday from the output below:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
2. Print the number of elements showing below:
Jher
Ryan
Derech
Mervin
3. Provide the output of the code below:
class Stack:
References
Ejonavi, J. (2020). Data Structures 101: how to use Stacks and Queues in Java. Retrieved
2021, from Educative: https://www.educative.io/blog/data-structures-stack-
queue-java-tutorial
Linked List implementation of Queue. (n.d.). Retrieved 2021, from Java T. Point:
https://www.javatpoint.com/linked-list-implementation-of-queue
Linked list implementation of stack. (n.d.). Retrieved 2021, from Java T Point:
https://www.javatpoint.com/ds-linked-list-implementation-of-stack