Jul 23 - Data Structure
Jul 23 - Data Structure
Learning Outcomes
Data structure – refers to a scheme for organizing data, or in other words a data structure is
an arrangement of data in computer's memory in such a way that it could make the data
quickly available to the processor for required calculations. A data structure should be seen
as a logical concept that must address two fundamental concerns. First, how the data will be
stored, and second, what operations will be performed on it? As data structure is a scheme
for data organization so the functional definition of a data structure should be independent of
its implementation.
Example:
A calculator app stores previous results in memory using a list, allowing you to recall or redo
operations.
Easy Example:
Like keeping tools in a toolbox where each type has its own section—so you find what you
need fast.
Example:
In a music player, songs are stored in a queue so they play one after another.
Easy Example:
Like lining up songs in a playlist:
1
The concept of a data structure focuses on what it does, not how it's coded. The logic
remains the same even in different programming languages.
Example:
A stack works the same whether coded in Java, Python, or C++.
Easy Example:
Like playing the same game on different consoles—rules stay the same, just different
controllers.
ADT (Abstract Data Type) – The functional definition of a data structure is known as ADT
(Abstract Data Type) which is independent of implementation. The Implementation part is left
on developers who decide which technology better suits to their project needs.
Example:
A Stack ADT lets you push and pop items (like undo actions), but doesn’t say whether it’s
built using an array or linked list.
Easy Example:
Like describing a vending machine:
Data Structure – is specialized format to store and organized data in a computer's memory
or disk.
Example:
An array stores a list of student names in a fixed order in memory.
Easy Example:
Like putting books in numbered shelves so you know exactly where each book is.
Visual:
Computer Memory:
[0] → "Anna"
[1] → "Ben"
[2] → "Cara"
(Data stored in organized, accessible format)
Data structure – is also a collection of variables, possibly of several different data types
connected in various ways.
Example:
A structure (or record) that stores a student’s name (string), age (integer), and grade (float)
together.
2
Easy Example:
Like a folder that holds a student’s ID, photo, and report card—different types of information
grouped together.
Visual:
Student Record:
{
Name: "Lena" → [Text]
Age: 18 → [Number]
Grade: 89.5 → [Decimal]
}
(A collection of different data types stored together)
Data structures – can be broadly classified in two categories linear structures and
hierarchical structures. Arrays, linked lists, stacks, and queues are linear structures, while
trees, graphs, heaps etc. are hierarchical structures.
– Every data structure has its own strengths, and weaknesses. Also, every data structure
specially suits to specific problem types depending upon the operations performed and the
data organization. For example, an array is suitable for read operations. Following is a quick
introduction to important data structures.
Example:
Test scores like 85, 92, 78 before calculating the average.
Easy Example:
Like ingredients (flour, sugar, eggs) before baking a cake—they're raw and unprocessed.
Visual:
Raw Data:
[85] [92] [78]
Structure – refers to the way in which the parts of a system or object are arranged or
organized, or a system arranged in this way.
Example:
Stores a list of exam scores: [85, 90, 78, 92]
Easy Example:
Like numbered lockers—each item has a fixed position.
3
Visual:
Index: 0 1 2 3
Data: 85 90 78 92
2. Linked List
Example:
A dynamic list of names: Anna → Ben → Cara → Dave
Easy Example:
Like a train, where each coach links to the next.
Visual:
3. Stacks
Example:
Used in undo actions: Action3 → Action2 → Action1
Easy Example:
Like stacking plates—last in, first out (LIFO).
Visual:
Top → [Action3]
[Action2]
[Action1]
4. Queues
Example:
Printer jobs line: Job1 → Job2 → Job3
Easy Example:
Like a line at a cashier—first in, first out (FIFO).
Visual:
5. Trees
Example:
Represents folder structure in a file system.
4
Easy Example:
Like a family tree with parent-child relationships.
Visual:
Root
/ \
Left Right
/ \
Child1 Child2
6. Hash Tables
Example:
Stores key-value pairs: {"ID101": "Anna", "ID102": "Ben"}
Easy Example:
Like a dictionary—you look up a word (key) to get its meaning (value).
Visual:
Key → Value
"ID101" → "Anna"
"ID102" → "Ben”
Data Types – These are the data that a variable can hold in a programming language, that
we need to determine the type of data which is being stored into the memory of the
computer.
– All programming languages have a set of built-in data types
Example:
int age = 18; → The variable age holds an integer type.
Easy Example:
Like choosing the right container for what you’re storing: use a bottle for water, a box for
shoes.
Visual:
Data Types:
- int → 123 (whole number)
- float → 12.5 (decimal number)
- char → 'A' (single letter)
- string → "Hello" (text)
- bool → true/false (yes or no)
5
Abstract Data Types – The specification of a set of data and set of operations performed in
a data. The storage for data defined in terms of set of operations to be performed on the
data.
Example:
A Queue ADT defines operations like enqueue, dequeue, and peek, without saying how it's
stored.
Easy Example:
Like a remote control—you know what buttons do (volume up, channel change), but not how
it works inside.
Visual:
Example:
An algorithm to sort numbers from smallest to largest (e.g., bubble sort).
Easy Example:
Like a recipe for baking a cake—step-by-step instructions to get the final result.
Visual:
Example:
1. Apply to wet hair
2. Massage gently
3. Leave on for a few moments
4. Rinse off
Criteria for Algorithm – Every algorithm must satisfy the following criteria:
1. Input – zero or more quantities are externally supplied.
Example:
Accepting two numbers from a user.
6
Easy Example:
Like a recipe needing ingredients before cooking.
Visual:
Input → [5, 3]
Example:
Produces the sum of two numbers.
Easy Example:
Like the finished cake from following a recipe.
Visual:
Output → [8]
Example:
“Add A and B” is clear; “Maybe add A” is not.
Easy Example:
Like step-by-step instructions that make sense (not “Do something cool”).
Visual:
Clear: Add 2 + 3
Unclear: Add something to something
4. Finiteness – all instructions of an algorithm will terminate after a finite number of steps.
Example:
The algorithm must stop after a number of steps.
Easy Example:
Like a game with an end—no infinite play.
Visual:
Example:
Each step must be doable (e.g., basic math operations).
7
Easy Example:
Like using tools and steps you actually have at home to cook.
Visual:
✔ Possible: Divide 10 by 2
✘ Not Possible: Divide 10 by a unicorn
Inputs – These are the data items presented to the algorithms. An algorithm has either no
input or a predetermined number of them.
Example:
An algorithm that calculates the sum of two numbers takes num1 and num2 as inputs.
Easy Example:
Like giving ingredients to a recipe—flour and eggs go in first.
Visual:
Inputs:
num1 = 5
num2 = 10
→ Algorithm → Output: 15
Outputs – These are data items presented to the outside world as the result of the
execution of a program based on the algorithms. An algorithm ought to produce a least one
output.
Example:
After adding two numbers, the algorithm gives the result 15 as output.
Easy Example:
Like the cake you get after following a recipe—the final result.
Visual:
Inputs: 5 + 10
→ Algorithm →
Output: 15
Procedures – These are essential tool in programming that generalizes the notion of an
operator. These are used to encapsulate parts of an algorithm by localizing in one section of
a program all the statements relevant to a certain aspect of a program.
Example:
A procedure named calculateTotal() contains all the steps to compute a bill.
8
Easy Example:
Like a mini-recipe inside a cookbook—you use it every time you need to bake the same
cake.
Visual:
Main Program
↓
[Procedure: calculateTotal()]
- Add prices
- Apply tax
- Return total
Example:
Raw scores: 80, 85, 90 → Algorithm calculates the average → Output: 85
Easy Example:
Like turning raw vegetables into a cooked dish using a recipe.
Visual:
Computer Science – also refers to the study of data which includes the following:
1. Machines that holds data
Example:
Computers, servers, smartphones that store and process information.
Easy Example:
Like a cabinet that holds all your documents.
Visual:
PC | Phone | Cloud
(Devices where data lives)
Example:
Programming languages like Python, C++, Java used to process data.
9
Easy Example:
Like using a recipe to tell someone how to cook a meal.
Visual:
Python: total = a + b
C++: int total = a + b;
3. Foundations which describe what kinds of refined data can be produced from raw
data
Example:
Algorithms and logic define what outputs can be generated from inputs.
Easy Example:
Like knowing that mixing flour + water = dough, but not cake yet.
Visual:
Example:
Using arrays, trees, graphs to store data logically.
Easy Example:
Like organizing files into folders and subfolders.
Visual:
Data
├── Images
├── Documents
└── Videos
Example:
Start
Set total = 0
10
For each number in the list:
Add number to total
Display total
End
Easy Example:
Like writing cooking steps in simple words before turning them into real code.
Visual:
Pseudocode:
- Looks like plain English
- Shows logic, not syntax
- Can be turned into real code
Example:
IF score > 75
PRINT "Passed"
ELSE
PRINT "Failed”
Example:
Start with: “Calculate student average”
Refine to:
1. Input 3 grades
2. Add grades
3. Divide by 3
4. Display result
Easy Example:
Like planning a trip:
Start with “Go to Baguio” → Then plan transportation, budget, stops, etc.
Visual:
11
Initial Idea: Calculate average
↓
Step 1: Get inputs
↓
Step 2: Add values
↓
Step 3: Divide total
↓
Final Step: Show average
→ Program Ready to Code
Example:
Comparing two sorting algorithms to see which one runs faster and uses less memory.
Easy Example:
Like choosing the fastest and most fuel-efficient route on Google Maps.
Visual:
Analysis Measures:
- Time (CPU time)
- Space (Memory used)
Analysis of Algorithms
1. Best – case analysis
Example:
Searching for the first item in a list — found immediately.
Easy Example:
Like finding your keys right where you left them.
Visual:
Example:
Searching for an item that's not in the list — you check every element.
12
Easy Example:
Like checking every drawer in your house before finding your keys.
Visual:
Example:
On average, you find the item after checking half the list.
Easy Example:
Like usually finding your keys in the 3rd out of 6 drawers.
Visual:
Example:
Problem:
Create an algorithm, pseudo codes and flowchart that will determine if the number if positive
or negative numbers. If the number is greater than zero display positive, otherwise display
negative.
Algorithm
1. Input number from the keyboard
2. Create condition
3. Display the result
Pseudo Codes
Enter number from the keyboard.
If the number is positive then
print positive
otherwise
print negative
Flowchart
13
Problem:
Create a program that will input grades for prelim, midterm and final and compute their final
average. Determine if the final average is greater than 75 then print Passed otherwise print
Failed. Convert it into, algorithm, pseudo codes and flowchart. Submit your activity within this
week once you finished studying the lesson.
1. Algorithm
1. Start
2. Input Prelim Grade
3. Input Midterm Grade
4. Input Final Grade
5. Compute Average = (Prelim + Midterm + Final) / 3
6. If Average >= 75, then display "Passed"
7. Else, display "Failed"
8. End
2. Pseudo Code
14
Start
Input Prelim
Input Midterm
Input Final
Set Average = (Prelim + Midterm + Final) / 3
If Average >= 75 Then
Display "Passed"
Else
Display "Failed"
End If
End
3. Flowchart Description
Flow:
[Start]
↓
[Input Prelim]
↓
[Input Midterm]
↓
[Input Final]
↓
[Compute Average = (Prelim + Midterm + Final) / 3]
↓
┌───────────────────────────────────┐
│ Is Average >= 75? │
└───────────────────────────────────┘
↓Yes ↓No
[Display "Passed"] [Display "Failed"]
↓ ↓
[End]
15
4. Sample Code (Python)
# Input grades
prelim = float(input("Enter Prelim Grade: "))
midterm = float(input("Enter Midterm Grade: "))
final = float(input("Enter Final Grade: "))
# Compute average
average = (prelim + midterm + final) / 3
# Output result
print(f"Average: {average:.2f}")
if average >= 75:
print("Passed")
else:
print("Failed")
Learning Outcomes
Array – is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Example:
An array to store 5 test scores: [85, 90, 78, 92, 88]
Easy Example:
Like a row of egg cartons—each slot holds one egg of the same kind.
Visual:
Example:
In the array [10, 20, 30], the values 10, 20, and 30 are elements.
16
Easy Example:
Like individual books placed on a shelf.
Visual:
Index – Each location of an element in an array has a numerical index, which is used to
Identify the element.
Example:
In [10, 20, 30], 10 is at index 0, 20 at index 1, and so on.
Easy Example:
Like shelf numbers used to find the exact position of each book.
Visual:
Index: 0 1 2
Array: [10] [20] [30]
Array Representation – Arrays can be declared in various ways in different languages. For
illustration, let's take Java array declaration.
Example:
In Java, an array can be declared and initialized like this:
Easy Example:
Like saying: "I want 4 boxes to store test scores" — and placing numbers inside them.
Visual:
Index: 0 1 2 3
Scores: [85] [90] [78] [92]
As per the above illustration, following are the important points to be considered:
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Arrayfruits[5]:
• Arrayfruits= ("Apple", "papaya", "atis", "santol", "mango")
• Arrayfruits[0];
17
• Each element can be accessed via its index. For example, we can fetch an element at
Index 6 as 9.
Basic Operations
Following are the basic operations supported by an array:
1. Traverse – print all the array elements one by one.
Example:
Printing elements of fruits[] = {"Apple", "Mango", "Banana"} from index 0 to 2.
Easy Example:
Like reading all the names on your class list one by one.
Visual:
Index: 0 1 2
Array: [Apple] [Mango] [Banana]
Example:
Insert "Orange" at index 1 → {"Apple", "Orange", "Mango"}
Easy Example:
Like putting a new book in between two books on a shelf.
Visual:
Example:
Remove the element at index 1 from {"Apple", "Orange", "Mango"} → {"Apple", "Mango"}
Easy Example:
Like removing a sandwich from the middle of your lunchbox.
Visual:
18
Example:
Find "Mango" in {"Apple", "Mango", "Banana"} → Found at index 1
Easy Example:
Like finding your name in the attendance list.
Visual:
Example:
Change index 2 value from "Banana" to "Grapes" → {"Apple", "Mango", "Grapes"}
Easy Example:
Like correcting a misspelled word in your school project.
Visual:
Example:
int nums[5] = {10, 20, 30, 40, 50};
nums[2] would access the value 30.
Easy Example:
Like a row of mailboxes numbered 0 to 4, each containing one item. To get the third letter,
you open box 2.
Visual:
Index: 0 1 2 3 4
[10] [20] [30] [40] [50]
2. Linked List
Example:
Node1 → Node2 → Node3 → NULL
19
Easy Example:
Like a treasure map where each clue (node) points to the next location (next node).
Visual:
Example:
Node1 → Node2 → Node3 → NULL
Easy Example:
Like a treasure map where each clue (node) points to the next location (next node).
Visual:
Example:
Dummy → Node1 → Node2 → NULL
Easy Example:
Like having a starting “marker” before the first real station on a train line.
Visual:
Example:
Use two arrays: one for data, one for “next” pointers.
Easy Example:
Like having a list of items in one column and directions to the next in another.
Visual:
3. Stacks
Example:
Push 10, Push 20, Pop → you get 20.
20
Easy Example:
Like stacking books: you take off the top book first.
Visual:
Top → [30]
[20]
[10]
4. Queues
Example:
Enqueue 10, Enqueue 20, Dequeue → you get 10.
Easy Example:
Like people lining up at a counter—first come, first served.
Visual:
Arrays – are statically implemented data structures by some programming languages like C
and C++; hence the size of this data structure must be known at compile time and cannot be
altered at run time. But modem programming languages, for example, Java implements
arrays as objects and give the programmer a way to alter the size of them at run time. Arrays
are the most common data structure used to store data.
Example:
In C:
In Java:
Easy Example:
21
Visual:
Java (Resizable):
Initial: [1] [2] [3] [4] [5]
Resize → [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
Arrays – are unarguably easier data structures to use and access. But inserting an item to
an array and deleting it from the array are situation dependent. if you want to insert an item
at a particular position which is already occupied by some element then you have to shift all
items one position right from the position new element has to be inserted then insert the new
item. The time taken by insert operation is depend on how big the array is, and at which
position the item is being inserted. The same is true about deletion of an item.
Example:
Original Array:
[10, 20, 30, 40]
Insert 25 at index 2:
Shift 30 and 40 → [10, 20, 25, 30, 40]
Delete at index 1:
Remove 20 and shift others → [10, 25, 30, 40]
Easy Example:
Visual:
Insert 25 at index 2
Before:
Index: 0 1 2 3
Array: [10][20][30][40]
After shifting:
Index: 0 1 2 3 4
Array: [10][20][25][30][40]
Delete at index 1
22
Before:
Index: 0 1 2 3
Array: [10][20][25][30]
After deletion:
Index: 0 1 2
Array: [10][25][30]
Arrays – If the array is unsorted then search operation is also proved costly and takes O(N)
time in worst case, where N is size of the array. But if the array is sorted then search
performance is improved magically and takes O(logN) time in worst case.
Example:
Unsorted Array:
[42, 17, 8, 91, 33]
Searching for 91: you may have to look at every element.
Sorted Array:
[8, 17, 33, 42, 91]
You can perform binary search — check the middle value, then eliminate half each time.
Easy Example:
Unsorted: Like looking for your keys in a messy room — you check every spot.
Sorted: Like looking for a word in a dictionary — you skip pages smartly using alphabetical
order.
Visual:
Time: O(N)
[8][17][33][42][91]
23
Time: O(log N)
Example:
Easy Example: Think of a train with several coaches (each coach holds one item).
Visual:
Index → 0 1 2 3 4
Marks → [89][78][92][84][75]
2. Two Dimensional Array – A table or matrix-like structure with rows and columns. Each
element is accessed using two indices.
Example:
Matrix[2][3] = [
[1, 2, 3],
[4, 5, 6]
]
Matrix[1][2] = 6
Easy Example:
Like a chessboard — rows and columns, and each square has something.
Visual:
Matrix:
Col0 Col1 Col2
Row0 → [ 1 ][ 2 ][ 3 ]
Row1 → [ 4 ][ 5 ][ 6 ]
24
Problem 1: Student Grades Average
Scenario: Create a program that accepts the grades of 5 students and computes the
average grade
Activity:
1. Declare an array to store 5 grades.
2. Ask the user to input each grade.
3. Compute and display the average.
25
Problem 2: Sales of Products
Scenario: A store sells 3 products. Each product's sales are recorded over 4 weeks. Create
a program that stores this data in a 2D array and computes the total sales per product and
total sales per week.
Activity:
1. Use a 2D array sales[3][4] for 3 products x 4 weeks.
2. Fill in the array using user input.
3. Display:
26
Activity 3: Reverse an Array (1D)
Task: Ask user for 5 numbers, store them in an array, and print them in reverse order.
import java.util.Scanner;
27
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[5];
// Input 5 numbers
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
System.out.print("Number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
scanner.close();
}
}
Task: Ask the user for a number, then search if it exists in a 3x3 matrix
import java.util.Scanner;
28
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == search) {
found = true;
break;
}
}
if (found) break;
}
// Display result
if (found) {
System.out.println("Number Found");
} else {
System.out.println("Number Not Found");
}
scanner.close();
}
}
Linked List – Linked list data structure provides better memory management than arrays.
Because linked list is allocated memory at run time, so, there is no waste of memory.
Performance wise linked list is slower than array because there is no direct access to linked
list elements.
Example:
Easy Example:
Imagine a treasure map, where each clue leads you to the next spot. You can't jump
ahead—you have to follow one by one.
Visual:
Linked list – is proved to be a useful data structure when the number of elements to be
stored is not known ahead of time.
29
Example:
A music playlist where you keep adding songs while listening. You don’t know how many
songs you’ll add, but you can always insert a new song at any point.
Easy Example:
Imagine a growing train—you can keep adding more train cars anytime, one after another,
without needing to know how long the train will be.
Visual:
There are many flavors of linked list you will see: linear, circular, doubly, and doubly circular.
30
Activities:
1. Rearranging
31
1.1 ALGORITHM → MHTIROGLA
Before:
A → L → G → O → R → I → T → H → M → NULL
After:
M → H → T → I → R → O → G → L → A → NULL
Before:
After:
2. Insertion
Before:
After:
Before:
After:
3. Deletion
32
3.1 Delete "LOGY" from "COMPUTER TECHNOLOGY"
Before:
After:
Before:
A → L → G → O → R → I → T → H → M → NULL
After:
A → L → G → O → R → I → NULL
Assignment:
Give and draw your own 5 examples of Rearranging, Insertion and Deletion Operations.
Write it in 1 whole bond paper long or MSWord
1.1
Before:
B → O → O → K → NULL
After:
K → O → O → B → NULL
1.2
Before:
M → A → T → H → NULL
After:
H → T → A → M → NULL
33
1.3
Before:
S → T → U → D → Y → NULL
After:
Y → D → U → T → S → NULL
1.4
Before:
F → R → U → I → T → NULL
After:
T → I → U → R → F → NULL
1.5
Before:
C → O → D → E → NULL
After:
E → D → O → C → NULL
2.1
2.2
2.3
34
2.4
2.5
3.1
Delete "TIRED"
Before:
I → AM → TIRED → NOW → NULL
After:
I → AM → NOW → NULL
3.2
Delete "OLD"
Before:
DELETE → OLD → FILE → NULL
After:
DELETE → FILE → NULL
3.3
Delete "NOON"
Before:
MORNING → NOON → NIGHT → NULL
After:
MORNING → NIGHT → NULL
3.4
Delete "FAIL"
Before:
TRY → FAIL → TRY → NULL
After:
35
TRY → TRY → NULL
3.5
Delete "SAD"
Before:
BE → SAD → STRONG → NULL
After:
BE → STRONG → NULL
Scenario: Create a simple task manager that allows the user to add, view, and remove tasks
using a LinkedList.
Activity:
•Use LinkedList<String> to store tasks.
•Display menu: Add task, Remove task, View all tasks, Exit.
•Implement input/output using Scanner.
36
37
Problem 2: Student Records (Manual Linked List)
Scenario: Build a manual linked list for storing student names. Allow insertion, deletion, and
display of nodes. Add 20 student records, delete 10 student records and view student
records. Write the output of this program in the provided box.
1. Filename: LinkListMain.java
package linkedlistmain;
import java.util.Scanner;
public class LinkedListMain
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
StudentList list = new StudentList();
int choice;
do {
System.out.println("\n--- Student Linked List ---");
System.out.println("1. Add Student");
System.out.println("2. Delete Student");
System.out.println("3. View Students");
System.out.println("4. Exit");
System.out.print("Choose: ");
choice = input.nextInt();
input.nextLine();
switch (choice) {
case 1:
System.out.print("Enter student name: ");
list.add(input.nextLine());
break;
case 2:
System.out.print("Enter name to delete: ");
list.delete(input.nextLine());
break;
case 3:
System.out.println("Student List:");
list.display();
break;
case 4:
System.out.println("Exiting...");
break;
}
} while (choice != 4);
}
}
FileName: StudentList
package linkedlistmain;
38
class StudentList
{
Node head;
if (head.data.equals(name)) {
head = head.next;
return;
}
if (temp.next != null) {
temp.next = temp.next.next;
}
}
// Display list
public void display() {
Node temp = head;
while (temp != null) {
System.out.println("- " + temp.data);
temp = temp.next;
}
}
}
Filename: Node.Java
package linkedlistmain;
39
class Node
{
String data;
Node next;
Output:
Learning Outcomes
Introduction
Storage Allocation – In computer programming, storage allocation refers to how memory is
reserved for variables, data structures, and program instructions during program execution.
Efficient storage allocation is critical for performance, especially when managing large
amounts of data. Two primary structures for managing data in memory are arrays and linked
lists, each with its own characteristics, advantages, and trade-offs.
40
Example:
In C language:
struct Node {
int data;
struct Node* next;
};
Easy Example:
Imagine a bookshelf:
An array is like a fixed shelf with 5 slots. You can't add more slots once it's built.
A linked list is like a flexible chain of book holders. You can always add more holders
anytime.
Visual:
+-------+-------+-------+-------+-------+
| 10 | 20 | 30 | 40 | 50 |
+-------+-------+-------+-------+-------+
Index: 0 1 2 3 4
[10] -> [20] -> [30] -> [40] -> [50] -> NULL
41
memory to be allocated at compile time or dynamically in a single block, and inserting or
deleting elements especially in the middle can be costly in terms of performance.
Example:
Easy Example:
But if you want to insert a new egg in the middle, you need to shift all the others.
Visual:
+------+------+------+------+------+
| 10 | 20 | 30 | 40 | 50 |
+------+------+------+------+------+
Index: 0 1 2 3 4
Linked list – is a linear data structure where elements, called nodes, are stored in
non-contiguous memory locations. Each node contains data and a pointer (or reference) to
the next node. This structure allows dynamic memory allocation, meaning nodes can be
added or removed easily at runtime without the need to shift elements, making it more
flexible than arrays in many situations.
Example (Java-style):
class Node {
int data;
Node next;
Node(int value) {
data = value;
next = null;
}
}
42
You can then link them like:
Easy Example:
You can add or remove a bead anywhere without touching all of them.
Visual:
Example (Java-style):
class ArrayNode {
int data;
ArrayNode next;
ArrayNode(int value) {
data = value;
next = null;
}
}
class LinkedArray {
ArrayNode[] array = new ArrayNode[10]; // array of linked list nodes
}
43
Easy Example:
But you also want to easily add or remove books (like a linked list)
So you make each shelf adjustable, and use slots to hold linked books
Visual:
Index: 0 1 2 3 4
↓ ↓ ↓ ↓ ↓
[10] → [20] [null] [30] → [40]
Definition of Terms
1. Storage allocation – It is a place for storing information
Example: In Java, when you declare int[] numbers = new int[5];, the memory is allocated for
5 integers in an array.
Easy Example: Think of a drawer with 5 sections to put papers. Each section is a storage
space for one paper.
Visual:
2. Key [Next [head]] – refers to the information associated with the first item on the list
Example:
class Node {
int key;
Node next;
}
Node head = new Node();
head.key = 10;
head.next = new Node();
44
Accessing: head.key gives 10 → Key[Next[head]]
Easy Example: Imagine a train: the engine is head, and the value (number) it carries is the
key.
Visual:
[Head] → [10] → [ ]
3. Key[next[next[head] ]] – refers to the second item on the list.
Example:
Easy Example: In the train, if the engine is head, the third coach holds the third value.
Visual:
4. Parallel arrays – the structure can be built "on top of the data
Example:
Easy Example: Two lists, one for student names, another for their scores. The 1st student's
name is in names[0], and their score is in scores[0].
Visual:
45
Names: [ "Anna" ][ "Ben" ][ "Carl" ]
Ages : [ 18 ][ 20 ][ 22 ]
↑ ↑ ↑
index 0 index 1 index 2
Example:
Easy Example: A note card with a number written on it. That number is the key.
Visual:
[ Key = 5 ]
Example:
Easy Example: In a chain of paperclips, each paperclip is a node, and the part connecting to
the next clip is the next.
Visual:
Given:
Position 0 = Head
1=Z
46
Insert T after S.
INSTRUCTIONS:
47
INSTRUCTIONS: (7 DISTINCT LETTERS)
1. Insert PROJECT IN AN EMPTY LIST
2. Insert PROJ after Head
3. Insert E after R
4. Insert C after O
5. Insert T after J
48
Lesson3. Activities
Given ALGORITHM, Create your own instructions to design the storage allocation with array
linked list implementation.
Assignment
Think of 3 words with 5, 7 and 9 distinct letters of computer words. Create your own
instructions and storage allocation. MSWord
STORE
NETWORK
CUSTOMIZE
A. INSTRUCTIONS 1:
49
https://beginnersbook.com/2013/12/how-to-loop-linkedlist-in-java/
50
Activity in Laboratory
Write a program using linked list to display the above examples like SLAIT, PROJECT and
ALGORITHM.
Learning Outcomes
INTRODUCTION
Stack – is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO (Last In First Out) or FILO (First In Last Out).
51
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)/FILO(First
In Last Out) order.
Example:
In programming, when a function calls another function, and that function calls another, the
return happens in reverse order. This is managed using a stack.
Easy Example:
You always take the topmost plate when you need one.
So:
Plate 1 → Bottom
Plate 2 → Middle
Plate 3 → Top → Removed first
Visual:
52
[ Plate 3 ] ← Last In (removed first)
[ Plate 2 ]
[ Plate 1 ] ← First In (removed last)
Push – Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
Example:
1. Push(10) → [10]
Stack of boxes:
If the shelf can only hold 3, adding a 4th box will cause an overflow (it falls).
Visual:
Example:
53
Start with a stack:
[30, 20, 10] ← Top is 30
If there are no books left, and you try to remove one more, that’s an underflow.
Visual:
Example:
Stack:
[30, 20, 10] ← Top is 30
Peek() → returns 30
Easy Example:
54
Visual:
Stack:
[ 30 ] ← Top (Peek returns this)
[ 20 ]
[ 10 ]
After Peek:
[ 30 ]
[ 20 ] ← Nothing changed!
[ 10 ]
Example:
1. Stack: []
isEmpty() → true
isEmpty() → false
Easy Example:
Visual:
Empty Stack:
[ ] ← nothing here
↓
isEmpty() → true
Non-Empty Stack:
[ 20 ]
[ 10 ] ← has items
55
↓
isEmpty() → false
Example:
import java.util.Stack;
Easy Example:
Visual:
Syntax – Stack.lastElement()
Example:
56
colors.push("Red");
colors.push("Blue");
⚠️ ❌
✅
> No need to write: colors.lastElement("Blue") →
Just write: colors.lastElement() →
Easy Example:
Think of saying:
“Show me the top plate”
You don’t give any plate name — you just ask to see the top one.
Visual:
Stack:
[ Blue ] ← lastElement()
[ Red ]
Call: colors.lastElement()
Output: "Blue”
Return Value – The method returns the last element present in the Stack.
Example:
> The last element added was 10, so that’s what it returns.
Easy Example:
Visual:
Stack:
[ 10 ] ← lastElement() returns this
[5 ]
57
Return Value: 10
Implementation Styles
1. Array-based (fixed size) – Use a fixed-size array plus a "top" index. Before pushing,
check for overflow: before popping, check for underflow Unstop.
Example:
stack[++top] = 10;
stack[++top] = 20;
stack[++top] = 30;
Easy Example:
Imagine stacking 5 plates in a tray. You can only put a plate on top, and remove from top.
Visual:
Stack size: 5
[30][20][10][ ][ ] ← Stack (top = 2)
↑
Top
Example:
class Node {
int data;
Node next;
Node(int value) {
data = value;
next = null;
}
}
58
top = new Node(30, top);
Easy Example:
Imagine a chain of boxes where you always add a new box at the front.
Visual:
59
Example:
Given input:
60
ABC*D*E
1. Push A → [A]
2. Push B → [A, B]
3. Push C → [A, B, C]
5. Push D → [A, B, D]
7. Push E → [A, B, E]
Final Stack:
A→B→E
Visual:
61
Pop (*) B ← D removed
A
Push E E
B
A
1. DATA***STRUCT***URES_AND*****ALGORITHMS
2. INFORMATION TECHNOL*****OGY***
3. CUS***TOMI***ZING*** WIND****OWS**
Program 1:
// Java code to illustrate lastElement()
import java.util.*;
Program 2:
import java.util.*;
62
stack.add(15);
stack.add(30);
stack.add(20);
stack.add(5);
Hands-On Activity
1. Create a program that will input 10 different student names and display the last name that
you entered from the stack.
2. Create a program that will input 10 Even Numbers and display the first number that you
entered from the stack.
63