MODULE 10
MODULE TITLE: Stack
OVERVIEW
This module discusses the concept of stack and its implementation using linked list. Stack
operations and its time complexity are also discussed here.
MODULE OBJECTIVES:
At the end of this module, the students should be able to:
Describe how values are stored and accessed in a stack
Explain the time complexity of stack operations
Create programs performing different operations on a stack
132 | P a g e
PRE-TEST
Name: Score:
Section: Instructor: Date:
Directions: Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)
T | F 1. Just like array, stack is a non-linear data structure.
T | F 2. Stack follows the First In Last Out concept of adding and removing items in a list.
T | F 3. Stacks can be implemented using linked lists and arrays.
T | F 4. Non-linear data structures such as stacks arrange the data into a sequence and
follow some sort of order.
T | F 5. Push is a stack operation that adds an item at the beginning of the list.
T | F 6. Stack is said to be in an underflow condition if it is empty.
T | F 7. Stack is said to be in an overflow condition if it is full.
T | F 8. Stack removes an item at the head of the list.
T | F 9. Redo-undo features of Adobe Photoshop are applications of stack.
T | F 10. Adding an item to the stack takes O(n) time.
133 | P a g e
CONTENTS
A stack is a basic data structure that can be logically thought of as a linear structure represented
by a real physical stack or pile, a structure where insertion and deletion of items takes place at
one end called top of the stack. The basic implementation of a stack is also called a LIFO (Last
In First Out) to demonstrate the way it accesses data.
There are many real-life examples of a stack. Consider an example of plates stacked over one
another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate
which has been placed at the bottommost position remains in the stack for the longest period of
time. So, it can be simply seen to follow LIFO (Last In First Out) order.
The following are the basic stack operations:
Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow
condition.
134 | P a g e
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.
Time Complexities of Operations on Stack
push(), pop(), isEmpty() and peek() all take O(1) time. We do not run any loop in any of these
operations.
Applications of Stack
Redo-undo features at many places like editors, photoshop.
Forward and backward feature in web browsers
Used in many algorithms like Tower of Hanoi, and tree traversals.
Implementation
There are two ways to implement a stack:
Using array
Using linked list
Although a linked list implementation of a stack is possible (adding and deleting from the head
of a linked list produces exactly the LIFO semantics of a stack), the most common applications
for stacks have a space restraint so that using an array implementation is a natural and efficient
one (In most operating systems, allocation and de-allocation of memory is a relatively expensive
operation, there is a penalty for the flexibility of linked list implementations).
135 | P a g e
To further understand how a stack works, consider our sample program.
Node.java
public class Node {
// storage for the node data
private int data;
// storage for the address of the next node
private Node next;
// a no-argument constructor that creates a node with default values
public Node() {
data = 0;
next = null;
}
// a constructor that creates a node with initial data specified by the parameter
public Node(int data) {
this.data = data;
next = null;
}
// set and get methods
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Stacks.java
public class Stacks {
// storage for the address of the first node
private Node head;
// set and get methods for the first node
public Node getHead() {
return head;
}
136 | P a g e
public void setHead(Node head){
this.head = head;
}
// method for push operation
public void push(int number) {
Node node = new Node(number);
if(head==null)
head = node;
else {
Node currentNode = head;
while(currentNode.getNext()!=null)
currentNode = currentNode.getNext();
currentNode.setNext(node);
}
}
// method for pop operation
public int pop() {
int popValue = 0;
if(count()==1) {
popValue = head.getData();
head = null;
}
else {
Node currentNode = head;
for(int i=1; i<count()-1; i++)
currentNode = currentNode.getNext();
Node tempNode = currentNode.getNext();
popValue = tempNode.getData();
currentNode.setNext(null);
tempNode = null;
}
return popValue;
}
// method for peek operation
public int peek() {
Node currentNode = head;
while(currentNode.getNext()!=null)
currentNode = currentNode.getNext();
return currentNode.getData();
}
// method for isEmpty operation
public boolean isEmpty(){
boolean empty = false;
if(head==null)
empty=true;
return empty;
}
137 | P a g e
// method for counting the number of nodes in the stack
private int count() {
int ctr=0;
Node currentNode = head;
while(currentNode!=null) {
currentNode = currentNode.getNext();
ctr++;
}
return ctr;
}
// displays the contents of the stack
public void view() {
System.out.print("\nStack content: ");
Node currentNode = head;
while(currentNode!=null) {
System.out.print(currentNode.getData() + " ");
currentNode = currentNode.getNext();
}
}
}
MainProgram.java
import java.io.*;
public class MainProgram {
public static void main(String[ ] args) throws IOException {
Stacks stack = new Stacks();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("\nPopped: " + stack.pop());
System.out.print("\nPopped: " + stack.pop());
stack.push(4);
System.out.print("\nTop value: " + stack.peek());
stack.view();
}
}
The output of the program is:
138 | P a g e
POST-TEST
Name: Score:
Section: Instructor: Date:
I. True or False. Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)
T | F 1. A stack can only be implemented using linked list.
T | F 2. Non-linear data structures such as stacks arrange the data into a sequence and
follow some sort of order.
T | F 3. Stack removes an item at the head of the list.
T | F 4. Stack follows the First In Last Out concept of adding and removing items in a list.
T | F 5. Redo-undo features of Adobe Photoshop are applications of stack.
T | F 6. Stack is said to be in an underflow condition if it is empty.
T | F 7. Push is a stack operation that adds an item at the beginning of the list.
T | F 8. Removing an item from the stack takes O(1) time.
T | F 9. Stack is said to be in an overflow condition if it is full.
T | F 10. Adding an item from the stack takes O(1) time.
II. Multiple Answer Questions. Encircle the letter of the item that will answer the following
questions. Each question may have more than one answer. (2 points each)
1. Which of the following correctly describes stack data structure?
a. Stack implements the FILO concept in c. Stack can only be implemented using a
managing items in the list. linked list.
b. Stack inserts element at the end of the d. Stack is a non-linear data structure.
list.
2. Which of the following is a Stack operation?
a. add c. push
b. peek d. insert
3. Which of the following is an application of stack?
a. forward and backward feature of web c. line in a bus ticket window
browsers
139 | P a g e
b. redo-undo features of Adobe Photoshop d. Tower of Hanoi game
4. Which of the following correctly describes push operation?
a. It adds an item at the tail of the list. c. Its time complexity is O(1).
b. It adds an item at the head of the list. d. It may cause stack underflow.
5. Which of the following correctly described pop operation?
a. It removes an item at the tail of the list. c. Its time complexity is O(1).
b. It removes an item at the head of the list. d. It may cause stack underflow.
140 | P a g e
MODULE TEST
Name: Score:
Section: Instructor: Date:
I. True or False. Encircle ‘T’ if the statement is correct. Otherwise, encircle ‘F’. (10 points)
T | F 1. Removing an item from the stack takes O(1) time.
T | F 2. Stack is said to be in an underflow condition if it is empty.
T | F 3. Non-linear data structures such as stacks arrange the data into a sequence and
follow some sort of order.
T | F 4. Stack removes an item at the head of the list.
T | F 5. Stack is said to be in an overflow condition if it is full.
T | F 6. A stack can only be implemented using linked list.
T | F 7. Stack follows the First In Last Out concept of adding and removing items in a list.
T | F 8. Redo-undo features of Adobe Photoshop are applications of stack.
T | F 9. Push is a stack operation that adds an item at the beginning of the list.
T | F 10. Adding an item from the stack takes O(1) time.
II. Programming
Problem
Using one-dimensional array of integers, create a program that will simulate the following stack
(LIFO) operations. (32 points)
a. Push - Adds an item to the stack.
b. Pop - Removes an item from the stack.
c. Peek - Returns the top (last) element of the stack.
d. isEmpty - Returns true if stack is empty, else false.
e. isFull - Returns true if stack is full, else false.
141 | P a g e
The size of the array must be defined first before displaying the menu for stack operation.
Sample Output
Enter size of the array? 10
[1] Push
[2] Pop
[3] Peek
[4] isEmpty
[5] isFull
[6] Exit
Enter choice: 1
Enter value to be pushed: 5
Successfully added an element!
[1] Push
[2] Pop
[3] Peek
[4] isEmpty
[5] isFull
[6] Exit
Enter choice: 3
Value of top is 5.
[1] Push
[2] Pop
[3] Peek
[4] isEmpty
[5] isFull
[6] Exit
Enter choice: 6
Good bye!
142 | P a g e
Grading Rubric
143 | P a g e
REFERENCES
Textbook:
[1] Malik D. S. 2019. C++ Programming including Data Structures. Cengage Learning.
Online Resources:
[2] HackerEarth. 2020. Basics of Stacks. Retrieved May 10, 2020 from
https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/tutorial/
[3] TutorialsPoint. 2020. Data Structures - Algorithms Basics. Retrieved May 10, 2020
https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm
[4] Friesen J. 2017. Data Structures and Algorithms in Java, Part 1: Overview. Retrieved May
10, 2020 from https://www.javaworld.com/article/3215112/java-101-datastructures-and-
algorithms-in-java-part-1.html
144 | P a g e