0% found this document useful (0 votes)
53 views

Unit - 2 Linear Data Structures (Stacks)

This document discusses stacks as a linear data structure. It defines a stack as a last-in, first-out (LIFO) structure for storing items with access limited to one end (the top). Common stack operations like push, pop, and peek are described along with their time complexities of O(1). Stacks can be implemented using arrays or linked lists. Example applications of stacks include undo/redo features, conversion between infix/postfix notation, backtracking algorithms, and memory management.

Uploaded by

Lavanya J
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Unit - 2 Linear Data Structures (Stacks)

This document discusses stacks as a linear data structure. It defines a stack as a last-in, first-out (LIFO) structure for storing items with access limited to one end (the top). Common stack operations like push, pop, and peek are described along with their time complexities of O(1). Stacks can be implemented using arrays or linked lists. Example applications of stacks include undo/redo features, conversion between infix/postfix notation, backtracking algorithms, and memory management.

Uploaded by

Lavanya J
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT - 2 LINEAR DATA STRUCTURES

(STACKS AND QUEUE)


STACKS
INTRODUCTION
• A stack is a data structure that is often likened to a
stack of plates.
• If you have just washed a plate, you put it on top of
the stack. When you need a plate, you take it off the
top of the stack. So the last plate to be added to the
stack will be the first to be removed from the stack.
• Thus, a stack is a last in, first out (LIFO) structure:
Definition of Stack
• A stack is a data structure that stores a linear
collection of items with access limited to a last-in
first-out order (LIFO).
• Adding and removing items is restricted to one end
known as the top of the stack. An empty stack is one
containing no items.
In other terms
• Stack is an abstract data type with a
bounded(predefined) capacity.
• It is a simple data structure that allows adding and
removing elements in a particular order.
• Every time an element is added, it goes on the top of
the stack and the only element that can be removed is
the element that is at the top of the stack, just like a pile
of objects.
Features of stack
1. Stack is an ordered list of similar data type.
2. Stack is a LIFO(Last in First out) structure or we can say
FILO(First in Last out).
3. push() function is used to insert new elements into the Stack
and pop() function is used to remove an element from the
stack. Both insertion and removal are allowed at only one
end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely
full and is said to be in Underflow state if it is completely
empty.
The following basic operations are performed in the stack:
• Push: Adds an item in the stack. If the stack is full, then it
is said to be an Overflow condition.
• Pop: Removes an item from the stack. The items are
popped in the reversed order in which they are pushed.
If the stack is empty, then it is said to be an Underflow
condition.
• Peek or Top: Returns top element of stack.
• isEmpty: Returns true if stack is empty, else false.
Implementation of Stack Data Structure
• Stack can be easily implemented using an
Array or a Linked List.
• Arrays are quick, but are limited in size and
Linked List requires overhead to allocate, link,
unlink, and de-allocate, but is not limited in
size.
Algorithm for PUSH operation
• Check if the stack is full or not.
• If the stack is full, then print error of overflow and
exit the program.
• If the stack is not full, then increment the top and add
the element.
Algorithm for POP operation
• Check if the stack is empty or not.
• If the stack is empty, then print error of underflow
and exit the program.
• If the stack is not empty, then print the element at the
top and decrement the top.
There are two ways to implement a stack: 
Using array :
Pros: Easy to implement. Memory is saved
as pointers are not involved. 
Cons: It is not dynamic. It doesn’t grow
and shrink depending on needs at runtime.
Using Linked List:
Pros: The linked list implementation of stack
can grow and shrink according to the needs
at runtime. 
Cons: Requires extra memory due to
involvement of pointers.
# Python program for implementation of stack # Function to remove an item from stack. It
# import maxsize from sys module decreases size by 1
# Used to return -infinite when stack is empty def pop(stack):
from sys import maxsize if (isEmpty(stack)):
return str(-maxsize -1) # return minus infinite
# Function to create a stack. It initializes size
of stack as 0 return stack.pop()
def createStack():
stack = [] # Function to return the top from stack without
removing it
return stack
def peek(stack):
if (isEmpty(stack)):
# Stack is empty when stack size is 0
return str(-maxsize -1) # return minus infinite
def isEmpty(stack):
return stack[len(stack) - 1]
return len(stack) == 0
# Driver program to test above functions
# Function to add an item to stack. It stack = createStack()
increases size by 1
push(stack, str(10))
def push(stack, item): push(stack, str(20))
stack.append(item) push(stack, str(30))
print(item + " pushed to stack ") print(pop(stack) + " popped from stack")
# Python program for linked list implementation def pop(self):
of stack if (self.isEmpty()):
# Class to represent a node return float("-inf")
class StackNode: temp = self.root
# Constructor to initialize a node self.root = self.root.next
def __init__(self, data): popped = temp.data
self.data = data return popped
self.next = None
class Stack: def peek(self):
# Constructor to initialize the root of linked if self.isEmpty():
list return float("-inf")
def __init__(self): return self.root.data
self.root = None # Driver code
stack = Stack()
def isEmpty(self): stack.push(10)
return True if self.root is None else stack.push(20)
False
stack.push(30)
print "% d popped from stack" % (stack.pop())
def push(self, data):
print "Top element is % d " % (stack.peek())
newNode = StackNode(data)
newNode.next = self.root
self.root = newNode
print "% d pushed to stack" % (data)
Analysis of Stack Operations
• Below mentioned are the time complexities for various
operations that can be performed on the Stack data
structure.
– Push Operation : O(1)
– Pop Operation : O(1)
– Top Operation : O(1)
– Search Operation : O(n)
• The time complexities for push() and pop() functions are
O(1) because we always have to insert or remove the data
from the top of the stack, which is a one step process.
Applications of stack
• Balancing of symbols
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop. Forward and backward
feature in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem,
histogram problem.
• Backtracking is one of the algorithm designing technique .Some example of back
tracking are Knight-Tour problem, N-Queen problem, find your way through maze
and game like chess or checkers in all this problems we dive into someway if that
way is not efficient we come back to the previous state and go into some another
path. To get back from current state we need to store the previous state for that
purpose we need stack.
• In Graph Algorithms like Topological Sorting and Strongly Connected Components
• In Memory management any modern  computer uses stack as the primary-
management for a running purpose. Each program that is running in a computer
system has its own memory allocations
• String reversal is also a another application of stack. Here one by one each
character get inserted into the stack. So the first character of string is on the bottom
of the stack and the last element of string is on the top of stack. After Performing
the pop operations on stack we get string in reverse order .

You might also like