Stacks
CC 104 – DATA STRUCTURES
Learning Objectives:
At the end of this lesson, learners should be able to:
Explain the concept of a stack and how it follows the LIFO
(Last-In, First-Out) principle.
Describe the difference between static (array-based) and
dynamic (pointer-based) implementations.
Create a stack using a linked list (pointers) in Java.
Implement basic stack operations: push, pop, peek, and
isEmpty..
Review
"What happens when you use the 'Back'
button in your browser?“
When you use the 'Back' button in your browser, it takes
you to the previous webpage you visited.
This action works like a stack data structure, where the
most recent pages you’ve visited are placed on top.
Pressing 'Back' pops the current page off the stack and
loads the previous one.
Review
"Have you ever stacked plates or boxes? What
happens when you remove the top item?"
When you remove the top item, you take the most
recently placed one.
The other items below stay in the same order.
This is similar to how a stack works in programming —
you can only access or remove the item at the top,
following the Last-In, First-Out (LIFO) principle.
Brief Recap
 A stack is a linear data structure that allows
adding (push) and removing (pop) elements
only at the top of the stack.
 2 Implementations:
1. Static implementation uses arrays;
2. Dynamic implementation uses pointers or
linked lists which allow flexibility in size.
What is a Pointer in Java?
In traditional languages like C or C++, a pointer is
a variable that stores the memory address of
another variable.
However, Java does not have explicit pointers like
those languages.
Instead, Java uses references, which behave
similarly to pointers but with important
differences:
What is a Pointer in Java?
🔍 Key Points:
In Java, objects are accessed through references.
A reference in Java is like a pointer — it points to
the location in memory where the object is stored.
Unlike C/C++, Java does not allow direct memory
access, making it safer and easier to manage.
Example:
In this example, next refers to another Node object.
It doesn’t store the value directly, but instead points to the
next node — this is how we create linked data structures
like linked lists or stacks using dynamic memory.
Stack Using Linked List
(Dynamic Implementation)
In Java, we use objects and references
(pointers) to implement linked lists.
Each element (node) has:
• data (the value),
• next (a pointer/reference to the next node).
The top of the stack refers to the most
recently added node.
What is a Node?
In data structures like linked lists or
stack implementations (using
pointers/references), a Node is a basic
building block that stores data and a
reference to the next node.
Node class Class Node {
Class Node {
This defines a Node class that will be used
This defines a Node class that will be used
to create node objects in a linked structure.
to create node objects in a linked structure.
Node class
int data;
int data;
This variable holds the
This variable holds the actual value
actual value or data
or data
the node is storing.
the node is storing.
It could be an integer, string, or any object
It could be an integer, string, or any object
type depending on your use case.
type depending on your use case.
Node class
Node next;
Node next;
This is a
This is a reference to the next node
reference to the next node in the
in the
structure (like the next item in a linked list or
structure (like the next item in a linked list or
stack).
stack).
Think of it as a
Think of it as a pointer
pointer to the next node.
to the next node.
Node class public Node(int data) {
public Node(int data) {
This is a
This is a constructor
constructor that is called
that is called
when a new
when a new Node
Node object is created.
object is created.
It takes an integer data as a
It takes an integer data as a
parameter.
parameter.
Node class
this.data = data;
this.data = data;
Assigns the passed value to
Assigns the passed value to
the current node's data field.
the current node's data field.
Node class
this.next = null;
this.next = null;
Sets the next reference to null
Sets the next reference to null
initially, meaning the node is not
initially, meaning the node is not
yet connected to any other
yet connected to any other
node.
node.
Why is it Important?
 This Node class is essential when building dynamic data
structures like:
Linked Lists
Stacks
Queues
 Each node knows its own data and where the next node
is — allowing us to link multiple nodes together in
memory dynamically.
Sample Codes
Sample Codes
• private Node top;
private Node top;
 This declares a private
This declares a private
variable top that holds a
variable top that holds a
reference to the topmost
reference to the topmost
node in the stack.
node in the stack.
 It serves as the entry point
It serves as the entry point
to the stack and helps
to the stack and helps
track the most recent item
track the most recent item
added (following the Last-
added (following the Last-
In, First-Out rule).
In, First-Out rule).
• public Stack() { top = null; }
public Stack() { top = null; }
 This is the
This is the constructor
constructor for
for
the Stack class.
the Stack class.
 It initializes the
It initializes the top
top to
to null
null,
,
which means the stack is
which means the stack is
empty when a new stack
empty when a new stack
object is created.
object is created.
Sample Codes
Sample Codes
Sample Codes
Sample Codes
Sample Codes
Sample Codes
Sample User Output Interface
Learning Objectives:
At the end of this lesson, learners should be able to:
Define and explain the concept of a Stack and its operations
(PUSH, POP, PEEK).
Implement a Stack using an array in Java.
Demonstrate understanding of Stack through writing Java
programs.
Analyze and trace stack operations step-by-step.
Apply stack operations to solve programming problems.
What is a stack?
It is an ordered group of homogeneous items of elements.
Elements are added to and removed from the top of the stack
(the most recently added items are at the top of the stack).
The last element to be added is the first to be removed (LIFO:
Last In, First Out).
What is a Stack?
• A Stack is a linear data structure which follows
the LIFO principle (Last In, First Out).
• The most recently added element is the first to be
removed.
• Common operations:
•PUSH: Add an element to the top.
•POP: Remove the top element.
•PEEK: View the top element without removing it.
•isEmpty(): Check if the stack is empty.
•isFull(): Check if the stack is full (for array
implementation).
Stack Specification
Definitions:
◦ MAX_ITEMS: Max number of items that might be on the
stack
◦ ItemType: Data type of the items on the stack
Operations
◦ MakeEmpty
◦ Boolean IsEmpty
◦ Boolean IsFull
◦ Push (ItemType newItem)
◦ Pop (ItemType& item)
Push (ItemType newItem)
Function: Adds newItem to the top of
the stack.
Preconditions: Stack has been initialized
and is not full.
Postconditions: newItem is at the top of
the stack.
Pop (ItemType& item)
Function: Removes topItem from stack and returns it in item.
Preconditions: Stack has been initialized and is not empty.
Postconditions: Top element has been removed from stack and item is
a copy of the removed element.
Step-by-Step Procedure:
1. Define an array to hold stack elements.
2. Define a variable top to track the top of the stack (initialized to -1).
3. Implement PUSH operation:
 Check if the stack is full.
 If not, increment top and insert the new element.
4. Implement POP operation:
 Check if the stack is empty.
 If not, remove the element at top and decrement top.
5. Implement PEEK operation:
 Return the element at top if the stack is not empty.
6. Display stack elements (optional but helpful for visualization).
PUSH Operation Algorithm:
POP Operation Algorithm:
PEEK Operation Algorithm:
Sample Codes
Stack Implementation
#include "ItemType.h"
// Must be provided by the user of the class
// Contains definitions for MAX_ITEMS and ItemType
class StackType {
public:
StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
int top;
ItemType items[MAX_ITEMS];
};
Stack Implementation (cont.)
StackType::StackType()
{
top = -1;
}
void StackType::MakeEmpty()
{
top = -1;
}
bool StackType::IsEmpty() const
{
return (top == -1);
}
Stack Implementation (cont.)
bool StackType::IsFull() const
{
return (top == MAX_ITEMS-1);
}
void StackType::Push(ItemType newItem)
{
top++;
items[top] = newItem;
}
void StackType::Pop(ItemType& item)
{
item = items[top];
top--;
}
Stack overflow
The condition resulting from trying to push an element onto a full stack.
if(!stack.IsFull())
stack.Push(item);
Stack underflow
The condition resulting from trying to pop an empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
Implementing stacks using
templates
Templates allow the compiler to generate multiple versions of a class type
or a function by allowing parameterized types.
It is similar to passing a parameter to a function (we pass a data type to a
class !!)
Implementing stacks using templates
template<class ItemType>
class StackType {
public:
StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
int top;
ItemType items[MAX_ITEMS];
};
(cont.)
Example using templates
// Client code
StackType<int> myStack;
StackType<float> yourStack;
StackType<StrType> anotherStack;
myStack.Push(35);
yourStack.Push(584.39);
The compiler generates distinct class types and gives its own internal
name to each of the types.
Function templates
The definitions of the member functions must be rewritten as function
templates.
template<class ItemType>
StackType<ItemType>::StackType()
{
top = -1;
}
template<class ItemType>
void StackType<ItemType>::MakeEmpty()
{
top = -1;
}
Function templates (cont.)
template<class ItemType>
bool StackType<ItemType>::IsEmpty() const
{
return (top == -1);
}
template<class ItemType>
bool StackType<ItemType>::IsFull() const
{
return (top == MAX_ITEMS-1);
}
template<class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
{
top++;
items[top] = newItem;
}
Function templates (cont.)
template<class ItemType>
void StackType<ItemType>::Pop(ItemType& item)
{
item = items[top];
top--;
}
Comments using templates
The template<class T> designation must precede the class method name
in the source code for each template class method.
The word class is required by the syntax of the language and does not
mean that the actual parameter must be the name of a class.
Passing a parameter to a template has an effect at compile time.
Implementing stacks using dynamic
array allocation
template<class ItemType>
class StackType {
public:
StackType(int);
~StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
int top;
int maxStack;
ItemType *items;
};
Implementing stacks using
dynamic array allocation (cont.)
template<class ItemType>
StackType<ItemType>::StackType(int max)
{
maxStack = max;
top = -1;
items = new ItemType[max];
}
template<class ItemType>
StackType<ItemType>::~StackType()
{
delete [ ] items;
}
Example: postfix expressions
Postfix notation is another way of writing arithmetic
expressions.
In postfix notation, the operator is written after the
two operands.
infix: 2+5 postfix: 2 5 +
Expressions are evaluated from left to right.
Precedence rules and parentheses are never needed!!
Example: postfix expressions
(cont.)
Postfix expressions:
Algorithm using stacks (cont.)
Postfix expressions:
Algorithm using stacks
WHILE more input items exist
Get an item
IF item is an operand
stack.Push(item)
ELSE
stack.Pop(operand2)
stack.Pop(operand1)
Compute result
stack.Push(result)
stack.Pop(result)
Write the body for a function that replaces each copy of an item in
a stack with another item. Use the following specification. (this
function is a client program).
ReplaceItem(StackType& stack, ItemType oldItem, ItemType
newItem)
Function: Replaces all occurrences of oldItem with newItem.
Precondition: stack has been initialized.
Postconditions: Each occurrence of oldItem in stack has been
replaced by newItem.
(You may use any of the member functions of the StackType, but
you may not assume any knowledge of how the stack is
implemented).
{
ItemType item;
StackType tempStack;
while (!Stack.IsEmpty()) {
Stack.Pop(item);
if (item==oldItem)
tempStack.Push(newItem);
else
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item);
}
}
1
2
3
3
5
1
1
5
3
Stack
Stack
tempStack
oldItem = 2
newItem = 5
Exercises
1, 3-7, 14, 12, 15, 18, 19

Stack Data Structure Implementations.ppt

  • 1.
    Stacks CC 104 –DATA STRUCTURES
  • 2.
    Learning Objectives: At theend of this lesson, learners should be able to: Explain the concept of a stack and how it follows the LIFO (Last-In, First-Out) principle. Describe the difference between static (array-based) and dynamic (pointer-based) implementations. Create a stack using a linked list (pointers) in Java. Implement basic stack operations: push, pop, peek, and isEmpty..
  • 3.
    Review "What happens whenyou use the 'Back' button in your browser?“ When you use the 'Back' button in your browser, it takes you to the previous webpage you visited. This action works like a stack data structure, where the most recent pages you’ve visited are placed on top. Pressing 'Back' pops the current page off the stack and loads the previous one.
  • 4.
    Review "Have you everstacked plates or boxes? What happens when you remove the top item?" When you remove the top item, you take the most recently placed one. The other items below stay in the same order. This is similar to how a stack works in programming — you can only access or remove the item at the top, following the Last-In, First-Out (LIFO) principle.
  • 5.
    Brief Recap  Astack is a linear data structure that allows adding (push) and removing (pop) elements only at the top of the stack.  2 Implementations: 1. Static implementation uses arrays; 2. Dynamic implementation uses pointers or linked lists which allow flexibility in size.
  • 6.
    What is aPointer in Java? In traditional languages like C or C++, a pointer is a variable that stores the memory address of another variable. However, Java does not have explicit pointers like those languages. Instead, Java uses references, which behave similarly to pointers but with important differences:
  • 7.
    What is aPointer in Java? 🔍 Key Points: In Java, objects are accessed through references. A reference in Java is like a pointer — it points to the location in memory where the object is stored. Unlike C/C++, Java does not allow direct memory access, making it safer and easier to manage.
  • 8.
    Example: In this example,next refers to another Node object. It doesn’t store the value directly, but instead points to the next node — this is how we create linked data structures like linked lists or stacks using dynamic memory.
  • 9.
    Stack Using LinkedList (Dynamic Implementation) In Java, we use objects and references (pointers) to implement linked lists. Each element (node) has: • data (the value), • next (a pointer/reference to the next node). The top of the stack refers to the most recently added node.
  • 10.
    What is aNode? In data structures like linked lists or stack implementations (using pointers/references), a Node is a basic building block that stores data and a reference to the next node.
  • 11.
    Node class ClassNode { Class Node { This defines a Node class that will be used This defines a Node class that will be used to create node objects in a linked structure. to create node objects in a linked structure.
  • 12.
    Node class int data; intdata; This variable holds the This variable holds the actual value actual value or data or data the node is storing. the node is storing. It could be an integer, string, or any object It could be an integer, string, or any object type depending on your use case. type depending on your use case.
  • 13.
    Node class Node next; Nodenext; This is a This is a reference to the next node reference to the next node in the in the structure (like the next item in a linked list or structure (like the next item in a linked list or stack). stack). Think of it as a Think of it as a pointer pointer to the next node. to the next node.
  • 14.
    Node class publicNode(int data) { public Node(int data) { This is a This is a constructor constructor that is called that is called when a new when a new Node Node object is created. object is created. It takes an integer data as a It takes an integer data as a parameter. parameter.
  • 15.
    Node class this.data =data; this.data = data; Assigns the passed value to Assigns the passed value to the current node's data field. the current node's data field.
  • 16.
    Node class this.next =null; this.next = null; Sets the next reference to null Sets the next reference to null initially, meaning the node is not initially, meaning the node is not yet connected to any other yet connected to any other node. node.
  • 17.
    Why is itImportant?  This Node class is essential when building dynamic data structures like: Linked Lists Stacks Queues  Each node knows its own data and where the next node is — allowing us to link multiple nodes together in memory dynamically.
  • 18.
  • 19.
    Sample Codes • privateNode top; private Node top;  This declares a private This declares a private variable top that holds a variable top that holds a reference to the topmost reference to the topmost node in the stack. node in the stack.  It serves as the entry point It serves as the entry point to the stack and helps to the stack and helps track the most recent item track the most recent item added (following the Last- added (following the Last- In, First-Out rule). In, First-Out rule). • public Stack() { top = null; } public Stack() { top = null; }  This is the This is the constructor constructor for for the Stack class. the Stack class.  It initializes the It initializes the top top to to null null, , which means the stack is which means the stack is empty when a new stack empty when a new stack object is created. object is created.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 28.
    Learning Objectives: At theend of this lesson, learners should be able to: Define and explain the concept of a Stack and its operations (PUSH, POP, PEEK). Implement a Stack using an array in Java. Demonstrate understanding of Stack through writing Java programs. Analyze and trace stack operations step-by-step. Apply stack operations to solve programming problems.
  • 29.
    What is astack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). The last element to be added is the first to be removed (LIFO: Last In, First Out).
  • 30.
    What is aStack? • A Stack is a linear data structure which follows the LIFO principle (Last In, First Out). • The most recently added element is the first to be removed. • Common operations: •PUSH: Add an element to the top. •POP: Remove the top element. •PEEK: View the top element without removing it. •isEmpty(): Check if the stack is empty. •isFull(): Check if the stack is full (for array implementation).
  • 31.
    Stack Specification Definitions: ◦ MAX_ITEMS:Max number of items that might be on the stack ◦ ItemType: Data type of the items on the stack Operations ◦ MakeEmpty ◦ Boolean IsEmpty ◦ Boolean IsFull ◦ Push (ItemType newItem) ◦ Pop (ItemType& item)
  • 32.
    Push (ItemType newItem) Function:Adds newItem to the top of the stack. Preconditions: Stack has been initialized and is not full. Postconditions: newItem is at the top of the stack.
  • 33.
    Pop (ItemType& item) Function:Removes topItem from stack and returns it in item. Preconditions: Stack has been initialized and is not empty. Postconditions: Top element has been removed from stack and item is a copy of the removed element.
  • 35.
    Step-by-Step Procedure: 1. Definean array to hold stack elements. 2. Define a variable top to track the top of the stack (initialized to -1). 3. Implement PUSH operation:  Check if the stack is full.  If not, increment top and insert the new element. 4. Implement POP operation:  Check if the stack is empty.  If not, remove the element at top and decrement top. 5. Implement PEEK operation:  Return the element at top if the stack is not empty. 6. Display stack elements (optional but helpful for visualization).
  • 36.
  • 37.
  • 38.
  • 39.
  • 47.
    Stack Implementation #include "ItemType.h" //Must be provided by the user of the class // Contains definitions for MAX_ITEMS and ItemType class StackType { public: StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top; ItemType items[MAX_ITEMS]; };
  • 48.
    Stack Implementation (cont.) StackType::StackType() { top= -1; } void StackType::MakeEmpty() { top = -1; } bool StackType::IsEmpty() const { return (top == -1); }
  • 49.
    Stack Implementation (cont.) boolStackType::IsFull() const { return (top == MAX_ITEMS-1); } void StackType::Push(ItemType newItem) { top++; items[top] = newItem; } void StackType::Pop(ItemType& item) { item = items[top]; top--; }
  • 50.
    Stack overflow The conditionresulting from trying to push an element onto a full stack. if(!stack.IsFull()) stack.Push(item); Stack underflow The condition resulting from trying to pop an empty stack. if(!stack.IsEmpty()) stack.Pop(item);
  • 51.
    Implementing stacks using templates Templatesallow the compiler to generate multiple versions of a class type or a function by allowing parameterized types. It is similar to passing a parameter to a function (we pass a data type to a class !!)
  • 52.
    Implementing stacks usingtemplates template<class ItemType> class StackType { public: StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top; ItemType items[MAX_ITEMS]; }; (cont.)
  • 53.
    Example using templates //Client code StackType<int> myStack; StackType<float> yourStack; StackType<StrType> anotherStack; myStack.Push(35); yourStack.Push(584.39); The compiler generates distinct class types and gives its own internal name to each of the types.
  • 54.
    Function templates The definitionsof the member functions must be rewritten as function templates. template<class ItemType> StackType<ItemType>::StackType() { top = -1; } template<class ItemType> void StackType<ItemType>::MakeEmpty() { top = -1; }
  • 55.
    Function templates (cont.) template<classItemType> bool StackType<ItemType>::IsEmpty() const { return (top == -1); } template<class ItemType> bool StackType<ItemType>::IsFull() const { return (top == MAX_ITEMS-1); } template<class ItemType> void StackType<ItemType>::Push(ItemType newItem) { top++; items[top] = newItem; }
  • 56.
    Function templates (cont.) template<classItemType> void StackType<ItemType>::Pop(ItemType& item) { item = items[top]; top--; }
  • 57.
    Comments using templates Thetemplate<class T> designation must precede the class method name in the source code for each template class method. The word class is required by the syntax of the language and does not mean that the actual parameter must be the name of a class. Passing a parameter to a template has an effect at compile time.
  • 58.
    Implementing stacks usingdynamic array allocation template<class ItemType> class StackType { public: StackType(int); ~StackType(); void MakeEmpty(); bool IsEmpty() const; bool IsFull() const; void Push(ItemType); void Pop(ItemType&); private: int top; int maxStack; ItemType *items; };
  • 59.
    Implementing stacks using dynamicarray allocation (cont.) template<class ItemType> StackType<ItemType>::StackType(int max) { maxStack = max; top = -1; items = new ItemType[max]; } template<class ItemType> StackType<ItemType>::~StackType() { delete [ ] items; }
  • 60.
    Example: postfix expressions Postfixnotation is another way of writing arithmetic expressions. In postfix notation, the operator is written after the two operands. infix: 2+5 postfix: 2 5 + Expressions are evaluated from left to right. Precedence rules and parentheses are never needed!!
  • 61.
  • 62.
  • 63.
    Postfix expressions: Algorithm usingstacks WHILE more input items exist Get an item IF item is an operand stack.Push(item) ELSE stack.Pop(operand2) stack.Pop(operand1) Compute result stack.Push(result) stack.Pop(result)
  • 64.
    Write the bodyfor a function that replaces each copy of an item in a stack with another item. Use the following specification. (this function is a client program). ReplaceItem(StackType& stack, ItemType oldItem, ItemType newItem) Function: Replaces all occurrences of oldItem with newItem. Precondition: stack has been initialized. Postconditions: Each occurrence of oldItem in stack has been replaced by newItem. (You may use any of the member functions of the StackType, but you may not assume any knowledge of how the stack is implemented).
  • 65.
    { ItemType item; StackType tempStack; while(!Stack.IsEmpty()) { Stack.Pop(item); if (item==oldItem) tempStack.Push(newItem); else tempStack.Push(item); } while (!tempStack.IsEmpty()) { tempStack.Pop(item); Stack.Push(item); } } 1 2 3 3 5 1 1 5 3 Stack Stack tempStack oldItem = 2 newItem = 5
  • 66.
    Exercises 1, 3-7, 14,12, 15, 18, 19