Stack Data Structure
Stack Data Structure
STRUCTURE
DEFINITION
A stack is a linear data structure which can be accessed only at
one of its ends for storing and retrieving data
In which items may be inserted or deleted only from one end called
top of the stack.
The order may be LIFO(Last In First Out) or FILO(First In Last
Out).
LIFO implies that the element that is inserted last, comes out first,
and
FILO implies that the element that is inserted first, comes out last.
STACK REPRESENTATION
APPLICATIONS
Reverse
Undo Mechanism
Recursion
Expression evaluation
Infix to Postfix and Prefix conversion
WHY COMPLEX….?
Stack is considered a complex data structure
because it uses other data structures for
implementation, such as Arrays, Linked lists.
STACK OPERATIONS
push() Adds a new element on the stack.
pop() Removes and returns the top element from the stack.
peek() Returns the top element on the stack without removing
it.
isFull() Checks if the stack is full.
isEmpty() Checks if the stack is empty.
STACK IMPLEMENTATION
(CONSTRAINTS/LIMITATIONS)
Pushing onto a full stack: Overflow
•When TOP=Stack_size
Popping an empty stack: Underflow
•TOP=NULL
BASIC OPERATIONS -
ARRAYS
push() Adds a new element on the
stack.
pop() Removes and returns the top
element from the stack.
peek() Returns the top element on
the stack.
isFull() Checks if the stack is full.
isEmpty() Checks if the stack is
empty.
def push(self, x):
if [Link] ==
ALGORITHM – PUSH [Link] - 1:
print("Stack Overflow")
return
return [Link][[Link]]
ALGORITHM - ISEMPTY
OPERATION
Returns true if the stack is empty, else false.
•Check for the value of top in stack.
The new node becomes the top of the stack, and the previous elements
remain linked below it.
Push Push
(12) (13)
LIST
Print ("Stack Underflow")
Pop ( ) Pop ()
if [Link] is None:
Time
print("Stack is Complexity: O(1)
Empty")
return -1
INFIX TO POSTFIX
EXPRESSION
Given a string s representing an infix expression
(A + B) * C
Parentheses () make sure A + B is handled first.
After that, result of (A + B) is multiplied by C.
That’s why in postfix, A B + comes before C *.
EXAMPLE - (A + B) * C
POSTFIX NOTATION
A+B*C
A + (B * C)
ABC*+
HOW TO SOLVE A POSTFIX
EXPRESSION
Input: s = a*(b+c)/d
Output: *a/+bcd
PREFIX TO INFIX
CONVERSION
Infix : (OPERAND1 OPERATOR OPERAND2).
• Example : (A+B) * (C-D)
Example:
Input : Prefix : *+AB-CD
Output : Postfix : AB+CD-*
Explanation : Prefix to Infix : (A+B) * (C-D)
Infix to Postfix : AB+CD-*
POSTFIX TO PREFIX
CONVERSION
Input : Postfix : AB+CD-*
Output : Prefix : *+AB-CD
Explanation : Postfix to Infix : (A+B) * (C-D)
Infix to Prefix : *+AB-CD