Unit no 5 stack
Unit no 5 stack
Stack
• A stack is a linear data structure that follows the Last In, First Out
(LIFO) principle, meaning the last element added to the stack is the
first one to be removed. It can be visualized as a collection of items
stacked on top of each other, similar to a stack of plates.
Key Characteristics of a Stack:
• LIFO Structure: The last element added is the first one to be removed.
• Limited Access: Elements can only be accessed from the top of the
stack.
• Dynamic Size: The size of a stack can grow or shrink as elements are
added or removed.
Common Use Cases of Stacks:
• Expression Evaluation: Stacks are used in evaluating arithmetic
expressions, especially in parsing and converting infix expressions to
postfix or prefix notation.
• Backtracking Algorithms: Stacks are employed in algorithms like
depth-first search (DFS) where we need to backtrack to explore other
paths.
Stack Abstract Data Type (ADT)
• An Abstract Data Type (ADT) defines a data structure purely in terms
of its behavior from the point of view of a user, specifically in terms of
the operations that can be performed on it, without specifying the
implementation details.
Basic Operations of Stack ADT:
• Push: Adds an element to the top of the stack.
• Pop: Removes and returns the top element of the stack.
• Peek (Top): Returns the top element without removing it from the
stack.
• IsEmpty: Checks if the stack is empty.
• Size: Returns the number of elements in the stack.
Representation of Stacks Using
Sequential Organization
• Stacks can be implemented in two main ways: Sequential
Organization and Linked Organization.
Stack Representation Using
Arrays:
Stack Operations Using Array
Representation:
Example of Stack Operations:
Multiple Stacks
• Sometimes, a program may require multiple stacks within the same
data structure. Multiple stacks can be implemented in various ways:
1. Using a Single Array:
• ou can use a single array to hold multiple stacks by dividing the array
into segments, with each stack having a fixed size. You can maintain
separate top indices for each stack.
Example: