SlideShare a Scribd company logo
Data Structures and
Algorithms
Week 2: Linked Lists
Ferdin Joe John Joseph, PhD
Faculty of Information Technology
Thai-Nichi Institute of Technology, Bangkok
Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
2
Linked node question
• Suppose we have a long chain of list nodes:
• We don't know exactly how long the chain is.
• How would we print the data values in all the
nodes?
data next
10
data next
990
list ...data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
3
Algorithm pseudocode
Start at the front of the list.
While (there are more nodes to print):
 Print the current node's data.
 Go to the next node.
How do we walk through the nodes of the list?
list = list.next;//is this a good idea?
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
4
Traversing a list?
• One (bad) way to print every value in the list:
while (list != null) {
System.out.println(list.data);
list = list.next;//move to next node
}
• What's wrong with this approach?
• (It loses the linked list as it prints it!)
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
5
A current reference
• Don't change list. Make another variable, and
change it.
• A ListNode variable is NOT a ListNode object
ListNode current = list;
• What happens to the picture above when we write:
current = current.next;
data next
10
data next
990
list
...
data next
20
current
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
6
Traversing a list correctly
• The correct way to print every value in the list:
ListNode current = list;
while (current != null) {
System.out.println(current.data);
current = current.next; // move to
next node
}
• Changing current does not damage the list.
data next
10
data next
990
list
...
data next
20
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
7
Linked List vs. Array
• Print list values:
ListNode list= ...;
ListNode current = list;
while (current != null) {
System.out.println(current.data
);
current = current.next;
}
• Similar to array code:
int[] a = ...;
int i = 0;
while (i < a.length) {
System.out.println(a[i]);
i++;
}
Description Array Code Linked List Code
Go to front of list int i = 0; ListNode current = list;
Test for more elements i < size current != null
Current value elementData[i] current.data
Go to next element i++; current = current.next;
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
8
A LinkedIntList class
• Let's write a collection class named
LinkedIntList.
• Has the same methods as ArrayIntList:
• add, add, get, indexOf, remove, size, toString
• The list is internally implemented as a chain of linked
nodes
• The LinkedIntList keeps a reference to its front as a
field
• null is the end of the list; a null front signifies an empty list
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
9
LinkedIntList class v1
public class LinkedIntList {
private ListNode front;
public LinkedIntList() {
front = null;
}
methods go here
}
front =
LinkedIntList
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
10
Basic Structure
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[])
{
// Creating an empty LinkedList
LinkedList<String> list = new LinkedList<String>();
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
11
Implementing add
// Adds the given value to the end of
the list.
public void add(int value) {
...
}
• How do we add a new node to the end of a list?
• Does it matter what the list's contents are before the
add?
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
12
Adding to an empty list
• Before adding 20: After:
• We must create a new node and attach it to the list.
front = front =
data next
20
element 0
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
13
The add method, 1st try
// Adds the given value to the end of
the list.
public void add(int value) {
if (front == null) {
// adding to an empty list
front = new ListNode(value);
} else {
// adding to the end of an
existing list
...
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
14
Adding to non-empty list
• Before adding value 20 to end of list:
• After:
front =
data next
42
data next
-3
front =
data next
42
data next
-3
data next
20
element 0 element 1 element 2
element 0 element 1
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
15
Don't fall off the edge!
• To add/remove from a list, you must modify the next
reference of the node before the place you want to
change.
• Where should current be pointing, to add 20 at the end?
• What loop test will stop us at this place in the list?
front =
data next
42
data next
-3
element 0 element 1
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
16
The add method
// Adds the given value to the end of the
list.
public void add(int value) {
if (front == null) {
// adding to an empty list
front = new ListNode(value);
} else {
// adding to the end of an existing
list
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
17
Implementing get
// Returns value in list at given
index.
public int get(int index) {
...
}
• Exercise: Implement the get method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
18
The get method
// Returns value in list at given
index.
// Precondition: 0 <= index < size()
public int get(int index) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
19
Implementing add
// Inserts the given value at the given
index.
public void add(int index, int value) {
...
}
• Exercise: Implement the two-parameter add method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
20
The add method
// Inserts the given value at the given index.
// Precondition: 0 <= index <= size()
public void add(int index, int value) {
if (index == 0) {
// adding to an empty list
front = new ListNode(value, front);
} else {
// inserting into an existing list
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = new ListNode(value,
current.next);
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
21
Implementing remove
// Removes the value at the given
index.
public void remove(int index, int
value) {
...
}
• Exercise: Implement the two-parameter add method.
front =
data next
42
data next
-3
data next
17
element 0 element 1 element 2
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
22
The remove method
LinkedList<String> list = new LinkedList<String>();
// Use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Output the list
System.out.println("LinkedList:" + list);
// Remove the head using remove()
list.remove("Geeks");
list.remove("20");
// Print the final list
System.out.println("Final LinkedList:" + list);
Output
LinkedList:[Geeks, for, Geeks, 10, 20]
Final LinkedList:[for, Geeks, 10]
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
23
Sample code
Implementation using Java
https://beginnersbook.com/2013/12/linkedlist-in-
java-with-example/
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
24
Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
25
Doubly Linked List
Recall that the deletion of an element at the tail is not easy because we
have to find the node before the tail (the last node) by link hopping.
head
next
element
next nextnext
element element element
Baltimore Rome Seattle Toronto
tail
This problem can be easily solved by using the double linked list.
- Ed. 2 and 3.: Chapter 4
- Ed. 4: Chapter 3
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
26
A node in a doubly linked list: A compound object that
stores a reference to an element and two references, called
next and prev, to the next and previous nodes, respectively.
Reference to
next node
Reference to an
element
next
Element
Node
Reference to
previous node
prev
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
27
For convenience, a doubly linked list has a header node and a
trailer node. They are also called sentinel nodes, indicating
both the ends of a list.
header
Baltimore Rome Seattle
trailer
Difference from singly linked lists:
- each node contains two links.
- two extra nodes: header and trailer, which contain no
elements.
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
28
Class DLNode
Here is an implementation of nodes for doubly
linked lists in Java:
public class DLNode {
private Object element;
private DLNode next, prev;
public DLNode() {
this( null, null, null );
}
public DLNode( Object e, DLNode p, DLNode n
) {
element = e;
next = n;
prev = p;
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
29
void setElement( Object newElem ) {
element = newElem;
}
void setNext( DLNode newNext ) {
next = newNext;
}
void setPrev( DLNode newPrev ) {
prev = newPrev;
}
Object getElement() {
return element;
}
DLNode getNext() {
return next;
}
DLNode getPrev() {
return prev;
}
}
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
30
Insertion of an Element at the
Head
Before the insertion:
header
Baltimore Rome Seattle
trailer
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
31
DLNode x = new DLNode();
x.setElement(new String(“Toronto”));
(x.element = new String(“Toronto”))
Have a new node:
header
Rome Seattle
trailer
Baltimore
Toronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
32
x.setPrev(header);
x.setNext(header.getNext());
(header.getNext()).setPrev(x);
header.setNext(x);
x.prev ← header;
x.next ← header.next;
header.next.prev ← x;
header.next ← x;
Update the links:
header
Rome Seattle
trailer
Baltimore
Toronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
33
After the insertion:
header
Rome Seattle
trailer
BaltimoreToronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
34
Deleting an Element at the Tail
Before the deletion:
header
Rome Seattle
trailer
BaltimoreToronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
35
((trailer.getPrev()).getPrev()).setNext(trailer);
trailer.setPrev((trailer.getPrev()).getPrev());
trailer.prev.prev.next ← trailer;
trailer.prev ← trailer.prev.prev;
Update the links:
header
Rome
Seattle
trailer
BaltimoreToronto
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
36
After the deletion:
header
Rome
trailer
Toronto Baltimore
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
37
Week 2
• Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
38
Circular Linked List
• Last node references the first node
• Every node has a successor
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
39
Circular Linked List
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
40
Dummy Head Nodes
• Dummy head node
• Always present, even when the linked list is empty
• Insertion and deletion algorithms initialize prev to
reference the dummy head node, rather than null
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
41
Applications
Applications of linked list in computer science
Implementation of stacks and queues
Implementation of graphs : Adjacency list representation of graphs is most popular which is uses linked
list to store adjacent vertices.
Dynamic memory allocation : We use linked list of free blocks.
Maintaining directory of names
Performing arithmetic operations on long integers
Manipulation of polynomials by storing constants in the node of linked list representing sparse matrices
Applications of linked list in real world
Image viewer – Previous and next images are linked, hence can be accessed by next and previous
button.
Previous and next page in web browser – We can access previous and next url searched in web
browser by pressing back and next button since, they are linked as linked list.
Music Player – Songs in music player are linked to previous and next song. you can play songs
either from starting or ending of the list.
Lecture series for Data Structures and
Algorithms, Data Science and Analytics, Thai-
Nichi Institute of Technology
42
Next Week
Stack
Queue
Implementation in Java
Lecture series for Data Structures and
Algorithms, Data Science and Analytics,
Thai-Nichi Institute of Technology
43

More Related Content

PDF
Data Structures and Algorithm - Week 9 - Search Algorithms
PDF
Data Structures and Algorithm - Week 3 - Stacks and Queues
PDF
Week 1 - Data Structures and Algorithms
PDF
Data Structures and Algorithm - Week 11 - Algorithm Analysis
PDF
Data Structures and Algorithm - Week 4 - Trees, Binary Trees
PDF
Data Structures and Algorithm - Week 8 - Minimum Spanning Trees
PDF
Data Structures and Algorithm - Week 5 - AVL Trees
PDF
Data Structures and Algorithm - Week 6 - Red Black Trees
Data Structures and Algorithm - Week 9 - Search Algorithms
Data Structures and Algorithm - Week 3 - Stacks and Queues
Week 1 - Data Structures and Algorithms
Data Structures and Algorithm - Week 11 - Algorithm Analysis
Data Structures and Algorithm - Week 4 - Trees, Binary Trees
Data Structures and Algorithm - Week 8 - Minimum Spanning Trees
Data Structures and Algorithm - Week 5 - AVL Trees
Data Structures and Algorithm - Week 6 - Red Black Trees

What's hot (20)

PPS
Data Structure
PPT
Stacks in algorithems & data structure
PPTX
Data Structure and Algorithms
PPT
Data Structures 8
PPT
Data Structures 7
PPT
Data Structures 6
PDF
geekgap.io webinar #1
PDF
Data structures and algorithm analysis in java
PPTX
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
PDF
PPTX
Introduction to data structure and algorithms
PPTX
5. Queue - Data Structures using C++ by Varsha Patil
PPTX
4. Recursion - Data Structures using C++ by Varsha Patil
PPTX
3. Stack - Data Structures using C++ by Varsha Patil
PPTX
Lecture 01 Intro to DSA
PPTX
Step By Step Guide to Learn R
PDF
Data Structures 01
PPTX
Lecture 1 and 2
PPT
Data structures
PPTX
Basic of Data Structure - Data Structure - Notes
Data Structure
Stacks in algorithems & data structure
Data Structure and Algorithms
Data Structures 8
Data Structures 7
Data Structures 6
geekgap.io webinar #1
Data structures and algorithm analysis in java
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
Introduction to data structure and algorithms
5. Queue - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
3. Stack - Data Structures using C++ by Varsha Patil
Lecture 01 Intro to DSA
Step By Step Guide to Learn R
Data Structures 01
Lecture 1 and 2
Data structures
Basic of Data Structure - Data Structure - Notes
Ad

Similar to Week 2 - Data Structures and Algorithms (20)

PPT
10-linked-list.ppt
DOCX
Updated Lab3.docx
PDF
DS Complete notes for Computer science and Engineering
PPT
03-Lists.ppt
PDF
Can somebody solve the TODO parts of the following problem- Thanks D.pdf
PPT
Chapter 5 ds
PDF
2a-Linked Listsxcxxcxxcxcxcxcxcxcxcxcxx.pdf
PPTX
Adt of lists
PDF
There are a couple of new methods that you will be writing for this pr.pdf
PPT
Data structures & algorithms lecture 3
PPTX
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
PPT
Lec-07 Queues.ppt queues introduction to queue
PPT
Topic 14 Linked Lists data type CS upload
PPTX
Data structure
PPTX
21CS32 DS Module 1 PPT.pptx
PPTX
EC2311 – Data Structures and C Programming
PPTX
Data Structure -List Stack Queue
PDF
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
PDF
9 python data structure-2
10-linked-list.ppt
Updated Lab3.docx
DS Complete notes for Computer science and Engineering
03-Lists.ppt
Can somebody solve the TODO parts of the following problem- Thanks D.pdf
Chapter 5 ds
2a-Linked Listsxcxxcxxcxcxcxcxcxcxcxcxx.pdf
Adt of lists
There are a couple of new methods that you will be writing for this pr.pdf
Data structures & algorithms lecture 3
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
Lec-07 Queues.ppt queues introduction to queue
Topic 14 Linked Lists data type CS upload
Data structure
21CS32 DS Module 1 PPT.pptx
EC2311 – Data Structures and C Programming
Data Structure -List Stack Queue
Fjdkkdnncmckkgkhkhkkhkhkhkhkhkhkhkhkhkhhl
9 python data structure-2
Ad

More from Ferdin Joe John Joseph PhD (20)

PDF
Invited Talk DGTiCon 2022
PDF
Week 12: Cloud AI- DSA 441 Cloud Computing
PDF
Week 11: Cloud Native- DSA 441 Cloud Computing
PDF
Week 10: Cloud Security- DSA 441 Cloud Computing
PDF
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
PDF
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
PDF
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
PDF
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
PDF
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
PDF
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
PDF
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
PDF
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
PDF
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
PDF
Hadoop in Alibaba Cloud
PDF
Cloud Computing Essentials in Alibaba Cloud
PDF
Transforming deep into transformers – a computer vision approach
PDF
Week 11: Programming for Data Analysis
PDF
Week 10: Programming for Data Analysis
PDF
Week 9: Programming for Data Analysis
PDF
Week 8: Programming for Data Analysis
Invited Talk DGTiCon 2022
Week 12: Cloud AI- DSA 441 Cloud Computing
Week 11: Cloud Native- DSA 441 Cloud Computing
Week 10: Cloud Security- DSA 441 Cloud Computing
Week 9: Relational Database Service Alibaba Cloud- DSA 441 Cloud Computing
Week 7: Object Storage Service Alibaba Cloud- DSA 441 Cloud Computing
Week 6: Server Load Balancer and Auto Scaling Alibaba Cloud- DSA 441 Cloud Co...
Week 5: Elastic Compute Service (ECS) with Alibaba Cloud- DSA 441 Cloud Compu...
Week 4: Big Data and Hadoop in Alibaba Cloud - DSA 441 Cloud Computing
Week 3: Virtual Private Cloud, On Premise, IaaS, PaaS, SaaS - DSA 441 Cloud C...
Week 2: Virtualization and VM Ware - DSA 441 Cloud Computing
Week 1: Introduction to Cloud Computing - DSA 441 Cloud Computing
Sept 6 2021 BTech Artificial Intelligence and Data Science curriculum
Hadoop in Alibaba Cloud
Cloud Computing Essentials in Alibaba Cloud
Transforming deep into transformers – a computer vision approach
Week 11: Programming for Data Analysis
Week 10: Programming for Data Analysis
Week 9: Programming for Data Analysis
Week 8: Programming for Data Analysis

Recently uploaded (20)

PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
Global journeys: estimating international migration
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
PDF
Lecture1 pattern recognition............
PPT
Quality review (1)_presentation of this 21
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
PPTX
IB Computer Science - Internal Assessment.pptx
PPTX
Business Acumen Training GuidePresentation.pptx
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PPTX
Introduction to Knowledge Engineering Part 1
PDF
Introduction to Business Data Analytics.
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
Global journeys: estimating international migration
Acceptance and paychological effects of mandatory extra coach I classes.pptx
oil_refinery_comprehensive_20250804084928 (1).pptx
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
Galatica Smart Energy Infrastructure Startup Pitch Deck
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
Lecture1 pattern recognition............
Quality review (1)_presentation of this 21
Introduction-to-Cloud-ComputingFinal.pptx
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
IB Computer Science - Internal Assessment.pptx
Business Acumen Training GuidePresentation.pptx
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
Introduction to Knowledge Engineering Part 1
Introduction to Business Data Analytics.
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf

Week 2 - Data Structures and Algorithms

  • 1. Data Structures and Algorithms Week 2: Linked Lists Ferdin Joe John Joseph, PhD Faculty of Information Technology Thai-Nichi Institute of Technology, Bangkok
  • 2. Week 2 • Linked Lists • Doubly Linked Lists • Circular Linked Lists Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 2
  • 3. Linked node question • Suppose we have a long chain of list nodes: • We don't know exactly how long the chain is. • How would we print the data values in all the nodes? data next 10 data next 990 list ...data next 20 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 3
  • 4. Algorithm pseudocode Start at the front of the list. While (there are more nodes to print):  Print the current node's data.  Go to the next node. How do we walk through the nodes of the list? list = list.next;//is this a good idea? data next 10 data next 990 list ... data next 20 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 4
  • 5. Traversing a list? • One (bad) way to print every value in the list: while (list != null) { System.out.println(list.data); list = list.next;//move to next node } • What's wrong with this approach? • (It loses the linked list as it prints it!) data next 10 data next 990 list ... data next 20 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 5
  • 6. A current reference • Don't change list. Make another variable, and change it. • A ListNode variable is NOT a ListNode object ListNode current = list; • What happens to the picture above when we write: current = current.next; data next 10 data next 990 list ... data next 20 current Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 6
  • 7. Traversing a list correctly • The correct way to print every value in the list: ListNode current = list; while (current != null) { System.out.println(current.data); current = current.next; // move to next node } • Changing current does not damage the list. data next 10 data next 990 list ... data next 20 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 7
  • 8. Linked List vs. Array • Print list values: ListNode list= ...; ListNode current = list; while (current != null) { System.out.println(current.data ); current = current.next; } • Similar to array code: int[] a = ...; int i = 0; while (i < a.length) { System.out.println(a[i]); i++; } Description Array Code Linked List Code Go to front of list int i = 0; ListNode current = list; Test for more elements i < size current != null Current value elementData[i] current.data Go to next element i++; current = current.next; Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 8
  • 9. A LinkedIntList class • Let's write a collection class named LinkedIntList. • Has the same methods as ArrayIntList: • add, add, get, indexOf, remove, size, toString • The list is internally implemented as a chain of linked nodes • The LinkedIntList keeps a reference to its front as a field • null is the end of the list; a null front signifies an empty list Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 9
  • 10. LinkedIntList class v1 public class LinkedIntList { private ListNode front; public LinkedIntList() { front = null; } methods go here } front = LinkedIntList Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 10
  • 11. Basic Structure import java.io.*; import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); } } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 11
  • 12. Implementing add // Adds the given value to the end of the list. public void add(int value) { ... } • How do we add a new node to the end of a list? • Does it matter what the list's contents are before the add? front = data next 42 data next -3 data next 17 element 0 element 1 element 2 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 12
  • 13. Adding to an empty list • Before adding 20: After: • We must create a new node and attach it to the list. front = front = data next 20 element 0 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 13
  • 14. The add method, 1st try // Adds the given value to the end of the list. public void add(int value) { if (front == null) { // adding to an empty list front = new ListNode(value); } else { // adding to the end of an existing list ... } } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 14
  • 15. Adding to non-empty list • Before adding value 20 to end of list: • After: front = data next 42 data next -3 front = data next 42 data next -3 data next 20 element 0 element 1 element 2 element 0 element 1 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 15
  • 16. Don't fall off the edge! • To add/remove from a list, you must modify the next reference of the node before the place you want to change. • Where should current be pointing, to add 20 at the end? • What loop test will stop us at this place in the list? front = data next 42 data next -3 element 0 element 1 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 16
  • 17. The add method // Adds the given value to the end of the list. public void add(int value) { if (front == null) { // adding to an empty list front = new ListNode(value); } else { // adding to the end of an existing list ListNode current = front; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 17
  • 18. Implementing get // Returns value in list at given index. public int get(int index) { ... } • Exercise: Implement the get method. front = data next 42 data next -3 data next 17 element 0 element 1 element 2 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 18
  • 19. The get method // Returns value in list at given index. // Precondition: 0 <= index < size() public int get(int index) { ListNode current = front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 19
  • 20. Implementing add // Inserts the given value at the given index. public void add(int index, int value) { ... } • Exercise: Implement the two-parameter add method. front = data next 42 data next -3 data next 17 element 0 element 1 element 2 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 20
  • 21. The add method // Inserts the given value at the given index. // Precondition: 0 <= index <= size() public void add(int index, int value) { if (index == 0) { // adding to an empty list front = new ListNode(value, front); } else { // inserting into an existing list ListNode current = front; for (int i = 0; i < index - 1; i++) { current = current.next; } current.next = new ListNode(value, current.next); } } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 21
  • 22. Implementing remove // Removes the value at the given index. public void remove(int index, int value) { ... } • Exercise: Implement the two-parameter add method. front = data next 42 data next -3 data next 17 element 0 element 1 element 2 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 22
  • 23. The remove method LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Output the list System.out.println("LinkedList:" + list); // Remove the head using remove() list.remove("Geeks"); list.remove("20"); // Print the final list System.out.println("Final LinkedList:" + list); Output LinkedList:[Geeks, for, Geeks, 10, 20] Final LinkedList:[for, Geeks, 10] Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 23
  • 24. Sample code Implementation using Java https://beginnersbook.com/2013/12/linkedlist-in- java-with-example/ Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 24
  • 25. Week 2 • Linked Lists • Doubly Linked Lists • Circular Linked Lists Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 25
  • 26. Doubly Linked List Recall that the deletion of an element at the tail is not easy because we have to find the node before the tail (the last node) by link hopping. head next element next nextnext element element element Baltimore Rome Seattle Toronto tail This problem can be easily solved by using the double linked list. - Ed. 2 and 3.: Chapter 4 - Ed. 4: Chapter 3 Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 26
  • 27. A node in a doubly linked list: A compound object that stores a reference to an element and two references, called next and prev, to the next and previous nodes, respectively. Reference to next node Reference to an element next Element Node Reference to previous node prev Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 27
  • 28. For convenience, a doubly linked list has a header node and a trailer node. They are also called sentinel nodes, indicating both the ends of a list. header Baltimore Rome Seattle trailer Difference from singly linked lists: - each node contains two links. - two extra nodes: header and trailer, which contain no elements. Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 28
  • 29. Class DLNode Here is an implementation of nodes for doubly linked lists in Java: public class DLNode { private Object element; private DLNode next, prev; public DLNode() { this( null, null, null ); } public DLNode( Object e, DLNode p, DLNode n ) { element = e; next = n; prev = p; } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 29
  • 30. void setElement( Object newElem ) { element = newElem; } void setNext( DLNode newNext ) { next = newNext; } void setPrev( DLNode newPrev ) { prev = newPrev; } Object getElement() { return element; } DLNode getNext() { return next; } DLNode getPrev() { return prev; } } Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 30
  • 31. Insertion of an Element at the Head Before the insertion: header Baltimore Rome Seattle trailer Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 31
  • 32. DLNode x = new DLNode(); x.setElement(new String(“Toronto”)); (x.element = new String(“Toronto”)) Have a new node: header Rome Seattle trailer Baltimore Toronto Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 32
  • 33. x.setPrev(header); x.setNext(header.getNext()); (header.getNext()).setPrev(x); header.setNext(x); x.prev ← header; x.next ← header.next; header.next.prev ← x; header.next ← x; Update the links: header Rome Seattle trailer Baltimore Toronto Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 33
  • 34. After the insertion: header Rome Seattle trailer BaltimoreToronto Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 34
  • 35. Deleting an Element at the Tail Before the deletion: header Rome Seattle trailer BaltimoreToronto Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 35
  • 36. ((trailer.getPrev()).getPrev()).setNext(trailer); trailer.setPrev((trailer.getPrev()).getPrev()); trailer.prev.prev.next ← trailer; trailer.prev ← trailer.prev.prev; Update the links: header Rome Seattle trailer BaltimoreToronto Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 36
  • 37. After the deletion: header Rome trailer Toronto Baltimore Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 37
  • 38. Week 2 • Linked Lists • Doubly Linked Lists • Circular Linked Lists Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 38
  • 39. Circular Linked List • Last node references the first node • Every node has a successor Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai- Nichi Institute of Technology 39
  • 40. Circular Linked List Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 40
  • 41. Dummy Head Nodes • Dummy head node • Always present, even when the linked list is empty • Insertion and deletion algorithms initialize prev to reference the dummy head node, rather than null Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai- Nichi Institute of Technology 41
  • 42. Applications Applications of linked list in computer science Implementation of stacks and queues Implementation of graphs : Adjacency list representation of graphs is most popular which is uses linked list to store adjacent vertices. Dynamic memory allocation : We use linked list of free blocks. Maintaining directory of names Performing arithmetic operations on long integers Manipulation of polynomials by storing constants in the node of linked list representing sparse matrices Applications of linked list in real world Image viewer – Previous and next images are linked, hence can be accessed by next and previous button. Previous and next page in web browser – We can access previous and next url searched in web browser by pressing back and next button since, they are linked as linked list. Music Player – Songs in music player are linked to previous and next song. you can play songs either from starting or ending of the list. Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai- Nichi Institute of Technology 42
  • 43. Next Week Stack Queue Implementation in Java Lecture series for Data Structures and Algorithms, Data Science and Analytics, Thai-Nichi Institute of Technology 43