0% found this document useful (0 votes)
3 views37 pages

Data Structures Lec 3-1

The document provides an overview of stacks as a linear data structure that follows the Last In First Out (LIFO) principle, detailing its basic operations such as push, pop, and top. It discusses two types of stack implementations: fixed size and dynamic size, along with their advantages and disadvantages. Additionally, it covers stack operations using arrays and linked lists, highlighting their respective benefits and applications.

Uploaded by

mntsr80awdail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Data Structures Lec 3-1

The document provides an overview of stacks as a linear data structure that follows the Last In First Out (LIFO) principle, detailing its basic operations such as push, pop, and top. It discusses two types of stack implementations: fixed size and dynamic size, along with their advantages and disadvantages. Additionally, it covers stack operations using arrays and linked lists, highlighting their respective benefits and applications.

Uploaded by

mntsr80awdail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Structures

Batch_16 _4 th semester
CS + IT+ IS Departments
Lecture 3: Stack

By: Hind Ali


Stack Overview
• Stack ADT
• Basic operations of stack
– Pushing, popping etc.
• Implementations of stacks using
– array
– linked list

6/22/2025 Sack 2
Stacks
A stack is a linear data structure where elements are
stored in the LIFO (Last In First Out) principle where the last
element inserted would be the f irst element to be deleted.
A stack is an Abstract Data Type (ADT), that is popularly
used in most programming languages. It is named stack
because it has the similar operations as the real-world
stacks, for example − a pack of cards or a pile of plates,
books etc.

6/22/2025 Sack 3
Stacks
 It is a linear data structure that follows a
particular order in which the operations are
performed.
 Add new items at the top.
 Remove an item at the top.
 Stack data structure similar to real life:
collection of elements arranged in a linear
order.
 Can only access element at the top
6/22/2025 Sack 4
Types of Stack:
• Fixed Size Stack :
As the name suggests, a f ixed size stack has a f ixed size
and cannot grow or shrink dynamically. If the stack is full
and an attempt is made to add an element to it, an
overf lo w error occurs. If the stack is empty and an
attempt is made to remove an element from it, an
underflow error occurs.

• Dynamic Size Stack :


A dynamic size stack can grow or shrink dynamically.
When the stack is full, it automatically increases its size
to accommodate the new element. This type of stack is
implemented using a linked list, as it allows for easy
resizing of the stack.

6/22/2025 Sack 5
Stack Operations
 Push(X) – insert X as the top element of
the stack
 Pop() – remove the top element of the
stack and return it.
 Top() – return the top element without
removing it from the stack.
 isEmpty() returns true if stack is empty
else false
 size() returns the size of stack
6/22/2025 Sack 6
Implementation of Stacks
• Any list implementation could be used to
implement a stack
– Arrays (static: the size of stack is given initially)
– Linked lists (dynamic: never become full)
• We will explore implementations based on
array and linked list
• Let’s see how to use an array to implement
a stack first

6/22/2025 Sack 7
Stack Operations

top 1
top 7 7
top 5 5 5
top 2 2 2 2
push(2) push(5) push(7) push(1)

top 21
top 7 7 top 7
5 5 5 top 5
2 2 2 2 top 2
1 pop() push(21) 21 pop() 7 pop() 5 pop()

6/22/2025 Sack 8
Push Operation in Stack:
The push() is an operation that inserts elements into the stack.
The following is an algorithm that describes the push()
operation in a simpler way.
Algorithm for Push Operation:
• Before pushing the element to the stack, we check if the
stack is full .
• If the stack is full (top == size-1) , then Stack Overflows and
we cannot insert the element to the stack.
• Otherwise, we increment the value of top by 1 (top = top + 1)
and the new value is inserted at top position .
• The elements can be pushed into the stack till we reach the
capacity of the stack.

6/22/2025 Sack 9
6/22/2025 Sack 10
Pop Operation in Stack:
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.
What happens if we call pop() and there is no element?
Algorithm for Pop Operation:
• Before popping the element from the stack, we
check if the stack is empty .
• If the stack is empty (top == -1), then Stack
Underflows and we cannot remove any element
from the stack.
• Otherwise, we store the value at top, decrement
the value of top by 1 (top = top – 1) and return
the stored top value.
6/22/2025 Sack 11
6/22/2025 Sack 12
Top or Peek Operation in Stack:
Returns the top element of the stack.
• Algorithm for Top Operation:
• Before returning the top element from the stack, we check if
the stack is empty.
• If the stack is empty (top == -1), we simply print “Stack is empty
”.
• Otherwise, we return the element stored at index = top .

6/22/2025 Sack 13
isEmpty Operation in Stack:
• IsEmpty() boolean function that returns true if stack is
empty, false otherwise.
• Returns true if the stack is empty, else false.
Algorithm for isEmpty Operation :
• Check for the value of top in stack.
• If (top == -1) , then the stack is empty so return true .
• Otherwise, the stack is not empty so return false .

6/22/2025 Sack 14
Display function

6/22/2025 Sack 15
Main code

6/22/2025 Sack 16
Advantages of Array Implementation:
• Easy to implement.
• Memory is saved as pointers are not involved.
Disadvantages of Array Implementation:
• It is not dynamic i.e., it doesn’t grow and
shrink depending on needs at runtime. [But in
case of dynamic sized arrays like vector in
C++, list in Python, ArrayList in Java, stacks
can grow and shrink with array
implementation as well.
• The total size of the stack must be defined
beforehand.

6/22/2025 Sack 17
Stack Using Linked List
• To implement a stack using a singly linked list, we
need to ensure that all operations follow the LIFO (Last
In, First Out) principle. This means that the most
recently added element is always the f irst one to be
removed. In this approach, we use a singly linked list,
where each node contains data and a reference (or link)
to the next node.
• To manage the stack, we maintain a top pointer that
always points to the most recent (topmost) node in the
stack.
• In the stack Implementation, a stack contains a top
pointer. which is the "head" of the stack where pushing
and popping items happens at the head of the list. The
f irst node has a null in the link f ield and second node-
link has the f irst node address in the link f ield and so
on and the last node address is in the "top" pointer.

6/22/2025 Sack 18
Stack Using Linked List
• We can avoid the size limitation of a stack
implemented with an array by using a
linked list to hold the stack elements.

6/22/2025 Sack 19
Stack Operations using Linked List

To implement a stack using a linked list, we need to set


the following things before implementing actual
operations.
• Step 1 - Include all the header files which are used in
the program. And declare all the user defined
functions.
• Step 2 - Define a 'Node' structure with two members
data and next.
• Step 3 - Define a Node pointer 'top' and set it to
NULL.
• Step 4 - Implement the main method by displaying
Menu with list of operations
6/22/2025 Sack
and make suitable 20
function calls in the main method.
Stack Using Linked List
• No need for the current pointer; head is enough.

head
top 1
1 7 5 2
7
5
2

6/22/2025 Sack 21
Define the Node Structure
First, we need to define the structure of a node in the linked
list. Each node will contain some data and a pointer to the
next node.
Initialize the top of the List
The head of the list is the first node in the list. Initially, the

list is empty, so the head is a null pointer.

6/22/2025 Sack 22
push(value) - Inserting an element into the Stack

6/22/2025 Sack 23
push( )

head
top 1
7 5 2
7
5
newNode 1
2

push(9)

6/22/2025 Sack 24
pop() - Deleting an Element from a Stack

1. Pre-requisites:
Ensure the stack is not empty before performing the
pop operation to avoid errors (stack underflow).
Step 1 - Check whether stack is Empty (top ==
NULL).
Step 2 - If it is Empty, then display "Stack is Empty!!!
Deletion is not possible!!!" and terminate the
function
Step 3 - If it is Not Empty, then define a Node pointer
'temp' and set it to 'top'.

Step 4 - Then set 'top = top next'.
Step 5 - Finally, delete 'temp'. (free(temp)).

6/22/2025 Sack 25
pop( )

head

1 7 5 2
top 7
5
2
6/22/2025 Sack 26
display() - Displaying stack of elements
We can use the following steps to display the
elements (nodes) of a stack...
• Step 1 - Check whether stack is Empty (top ==
NULL).
• Step 2 - If it is Empty, then display 'Stack is
Empty!!!' and terminate the function.
• Step 3 - If it is Not Empty, then define a Node
pointer ‘current' and initialize with top.

• Step 4 - Display ‘current data --->' and move it
to the next node. Repeat the same until current
reaches to the first node in the stack. (current
next != NULL).


• Step 5 - Finally! Display ‘current data ---> NULL'.
6/22/2025 Sack 27
6/22/2025 Sack 28
Main code

6/22/2025 Sack 29
dvantage of Linked List implementation:
• The linked list implementation of a stack
can grow and shrink according to the
needs at runtime.
Disadvantages of Linked List
implementation:
• Requires extra memory due to the
involvement of pointers.
• Random accessing is not possible in
stack.
6/22/2025 Sack 30
Stack: Array or List
• Since both implementations support stack
operations in constant time, any reason to
choose one over the other?
• Allocating and deallocating memory for list
nodes does take more time than preallocated
array.
• List uses only as much memory as required by
the nodes; array requires allocation ahead of
time.
• List pointers (head, next) require extra memory.
• Array has an upper limit; List is limited by
dynamic memory allocation.
6/22/2025 Sack 31
Advantages of Stack:

• Simplicity: Stacks are a simple and easy-to-understand


data structure, making them suitable for a wide range
of applications.
• Efficiency: Push and pop operations on a stack can be
performed providing efficient access to data.
• Last-in, First-out (LIFO): Stacks follow the LIFO
principle, ensuring that the last element added to the
stack is the first one removed. This behavior is useful
in many scenarios, such as function calls and
expression evaluation.
• Limited memory usage: Stacks only need to store the
elements that have been pushed onto them, making
them memory-efficient compared to other data
structures.

6/22/2025 Sack 32
Disadvantages of Stack:

• Limited access: Elements in a stack can only be


accessed from the top, making it difficult to retrieve
or modify elements in the middle of the stack.
• Potential for overflow: If more elements are pushed
onto a stack than it can hold, an overflow error will
occur, resulting in a loss of data.
• Not suitable for random access: Stacks do not allow
for random access to elements, making them
unsuitable for applications where elements need to
be accessed in a specific order.
• Limited capacity: Stacks have a fixed capacity, which
can be a limitation if the number of elements that
need to be stored is unknown or highly variable.

6/22/2025 Sack 33
• Applications of Stacks:
– Function Calls in Computers
– Memory Management
– Redo-Undo Features in Editors/Photoshop
– Forward and Backward Features in Web
Browsers

6/22/2025 Sack 34
Example use in C++
* indicates top
ArrayStack<int> A;
[Link](7);
[Link](13);
cout << [Link]() << endl; [Link]();
[Link](9);
cout << [Link]() << endl;
cout << [Link]() << endl; [Link]();

6/22/2025 Sack 35
Example use in C++
* indicates top
ArrayStack<int> A; // A = [ ], size = 0
[Link](7); // A = [7*], size = 1
[Link](13); // A = [7, 13*], size = 2
cout << [Link]() << endl; [Link](); // A = [7*], outputs: 13
[Link](9); // A = [7, 9*], size = 2
cout << [Link]() << endl; // A = [7, 9*], outputs: 9
cout << [Link]() << endl; [Link](); // A = [7*], outputs: 9

6/22/2025 Sack 36
END

6/22/2025 Sack 37

You might also like