0% found this document useful (0 votes)
35 views

Lecture 05-06 - Linked List

Uploaded by

caokhuong12311
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lecture 05-06 - Linked List

Uploaded by

caokhuong12311
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Data Structures and Algorithms


★ Linked List ★

Dr Vi Chi Thanh - [email protected]


https://vichithanh.github.io
Week by week topics (*)

1. Overview, DSA, OOP and Java 7. Advanced Sorting


2. Arrays 8. Binary Tree
3. Sorting 9. Hash Table
4. Queue, Stack 10.Graphs
5. List 11.Graphs Adv.
6. Recursion Final-Exam
Mid-Term 10 LABS

T UE SD AY , 2 2 O CT O BE R 2 0 24 2
Content

• Array Overview • Circular Lists


• Describe List structures • Double-ended list
• Describe self-referential • Sorted list
structures • Doubly Linked Lists
• Explain types of linked lists • Lists in java.util
• Singly Linked Lists

T UE SD AY , 2 2 O CT O BE R 2 0 24 3
Array review

• Arrays have some disadvantages


• Insertion is slow in ordered arrays
• Deletion is slow (ordered and unordered)
• Size of the array can’t be changed after creation

T UE SD AY , 2 2 O CT O BE R 2 0 24 4
Introduction to linked list

• Is the second widely used data structure


• Is suitable for many general-purpose databases
• Can replace an array in the implementation of Stack, Queue, etc.

T UE SD AY , 2 2 O CT O BE R 2 0 24 5
List Data Structures

• A list is a sequential data structure, i.e., it is a sequence of items of a given


base type, where items can be added, deleted, and retrieved from any
position in the list.
• A list can be implemented as an array, or as a dynamic array to avoid
imposing a maximum size.
• An alternative implementation is a linked list, where the items are stored in
nodes that are linked together with pointers. These two implementations
have very different characteristics.
• The possible values of this type are sequences of items of type BaseType
(including the sequence of length zero).

T UE SD AY , 2 2 O CT O BE R 2 0 24 6
Operations

• getFirst(), getLast(), getNext(p), getPrev(p), get(p), set(p,x), insert(p,x),


remove(p),removeFirst(), removeLast(), removeNext(p),
removePrev(p), find(x),size()

T UE SD AY , 2 2 O CT O BE R 2 0 24 7
Operations

• getFirst(), getLast(), getNext(p), getPrev(p), get(p), set(p,x), insert(p,x),


remove(p),removeFirst(), removeLast(), removeNext(p),
removePrev(p), find(x),size()

T UE SD AY , 2 2 O CT O BE R 2 0 24 8
Self-Referential Structures

• Many dynamic data structures are implemented through the use of a


self-referential structure.
• A self-referential structure is an object, one of whose elements is a
reference to another object of its own type.
• With this arrangement, it is possible to create ‘chains’ of data of
varying forms

T UE SD AY , 2 2 O CT O BE R 2 0 24 9
Self-Referential Structures
Employee
String name;
int age;

Linked lists trees

DataNode
DataNode
Employee info;
Employee info;
DataNode left;
DataNode next;
DataNode right;

Self-Referential Structures
T UE SD AY , 2 2 O CT O BE R 2 0 24 10
Linked Lists

• A linked structure is a collection of nodes storing data and links to other


nodes
• A linked list is a linear data structure composed of nodes, each node
holding some information and a reference to another node in the list
• Types of linked lists:
• Singly-Linked List
• Circular Lists
• Double-Ended List
• Doubly-Linked List

T UE SD AY , 2 2 O CT O BE R 2 0 24 11
Singly Linked Lists

• A singly linked list is a list whose node includes two data fields: info
and next. The info field is used to store information, and this is
important to the user. The next field is used to link to its successor in
this sequence
• The following image depicts a simple integer linked list.

head tail

Singly Linked List


T UE SD AY , 2 2 O CT O BE R 2 0 24 12
Simple linked list

T UE SD AY , 2 2 O CT O BE R 2 0 24 13
Link

• A link contains
• Data
• A reference to next link (‘Next’)

T UE SD AY , 2 2 O CT O BE R 2 0 24 14
Link class

T UE SD AY , 2 2 O CT O BE R 2 0 24 15
Relationship, not Position

• Can not access a data item directly.


• Must follow the chain from ‘First’ item

T UE SD AY , 2 2 O CT O BE R 2 0 24 16
Action on simple linked list

• Insertion
• Deletion
• Searching

T UE SD AY , 2 2 O CT O BE R 2 0 24 17
How would you do that - Insertion

• InsertFirst?

• InsertLast?

T UE SD AY , 2 2 O CT O BE R 2 0 24 18
In Java

T UE SD AY , 2 2 O CT O BE R 2 0 24 19
How would you do that - Deletion

• Delete first?

• Delete last?

T UE SD AY , 2 2 O CT O BE R 2 0 24 20
In Java

T UE SD AY , 2 2 O CT O BE R 2 0 24 21
How would you do that - Deletion

• Delete a link in the


middle of the list

T UE SD AY , 2 2 O CT O BE R 2 0 24 22
How would you do that - Display

T UE SD AY , 2 2 O CT O BE R 2 0 24 23
Practice

• LinkList2App.java
• Complete the functions:
• insertFirst
• find
• delete

T UE SD AY , 2 2 O CT O BE R 2 0 24 24
Circular List

T UE SD AY , 2 2 O CT O BE R 2 0 24 25
Circular Lists - 1
26

• A circular list is when nodes form a ring: The list is finite, and each
node has a successor

Circular Singly Linked List

Data Structures and Algorithms in Java 2 6/2 3


Circular Lists - 2
27
Inserting nodes

Inserting nodes at the front of a circular singly linked list (a) and at its end (b)
Data Structures and Algorithms in Java 2 7/2 3
Circular List application
28

• 1. Round-Robin Scheduling
• One of the most important roles of an operating system is in managing the
many processes that are currently active on a computer, including the
scheduling of those processes on one or more central processing units (CPUs).
• To support the responsiveness of an arbitrary number of concurrent processes,
most operating systems allow processes to effectively share use of the CPUs,
using some form of an algorithm known as round-robin scheduling.
• A process is given a short turn to execute, known as a time slice, but it is
interrupted when the slice ends, even if its job is not yet complete. Each active
process is given its own time slice, taking turns in a cyclic order.

Data Structures and Algorithms in Java 2 8/2 3


Circular List application
29

• 2. Using circular linked list to implement Round-Robin Scheduling


• We can use circular linked list to implement Round-Robin Scheduling by
the following method: rotate( ): Moves the first element to the end of the
list.
• With this new operation, round-robin scheduling can be efficiently
implemented by repeatedly performing the following steps on a circularly
linked list C:
1. Give a time slice to process C.first( )
2. C.rotate( )

Data Structures and Algorithms in Java 2 9/2 3


Double-Ended Lists

T UE SD AY , 2 2 O CT O BE R 2 0 24 30
Double-Ended Lists

In compare with Simple linked list, what are the advantages?

T UE SD AY , 2 2 O CT O BE R 2 0 24 31
Directly insert to last position

T UE SD AY , 2 2 O CT O BE R 2 0 24 32
How about the deletion of last item

• Unfortunately, it doesn’t help.


• Why?

T UE SD AY , 2 2 O CT O BE R 2 0 24 33
Simple linked list efficiency

• Insertion and deletion at beginning of the list are very fast: O(1)
• Finding, deleting, or insert item: O(n)
• → is it the same as array (O(n) also)?
• In comparison with array
• Don’t have to shift items to delete or insert.
• Uses exactly as much memory as it needs
• Size can be changed

T UE SD AY , 2 2 O CT O BE R 2 0 24 34
Abstract Data Type (ADT)

T UE SD AY , 2 2 O CT O BE R 2 0 24 35
ADT

• Is the way of looking at data structure focusing on


• WHAT it does
• NOT HOW it does
• Example:
• Stack: Pop, Push, Peek
• Queue: Enqueue, Dequeue
• → We can implement these data structure by Array or Linked List

T UE SD AY , 2 2 O CT O BE R 2 0 24 36
Implement Stack & Queue

• Implement Stack using Linked List: any idea?


• Push: InsertFirst
• Pop: DeleteFirst
• Peek: First
• Implement Queue using Linked List
• Enqueue: InsertLast
• Dequeue: DeleteFirst
• Stack/ Queue from the view of End-User: nothing change

T UE SD AY , 2 2 O CT O BE R 2 0 24 37
Data Types and Abstraction

• “Abstract”: data description is considered apart from detailed


specifications or implementation
• Abstract Data Type is a class considered without regard to its
implementation
• Classes vs Objects
• Classes are abstractions - Abstraction
• Individual objects – instantiations of those classes

T UE SD AY , 2 2 O CT O BE R 2 0 24 38
Data Types and Abstraction

• In OOP, we have ADTs.


• Have descriptions of fields and methods
• Contain NO details regarding the implementations.
• A client has access to the methods and how to invoke them, and what to
expect in return.
• A client DO NOT know how the methods are implemented

T UE SD AY , 2 2 O CT O BE R 2 0 24 39
Data Types and Abstraction and Interface

• Client knows that stack operations include a


• push(), pop(), isEmpty() and isFull().
• But have no knowledge as to how the data are stored (array, linked
list, tree, etc.) or accessed / processed in logical data structures.
• Client has no knowledge as to how
• push(), pop(), insert() and remove() are implemented.
• Client has no knowledge about the underlying implementing data structure.

T UE SD AY , 2 2 O CT O BE R 2 0 24 40
Interface in OOP

• The ADT specification: Interface.


• It provides what the client needs to see
• Example:
• public interface IStack
• void push(long value)
• long pop()

T UE SD AY , 2 2 O CT O BE R 2 0 24 41
ADTs as a Design Tool

• You are decoupling the specification of the ADT from its


implementation.
• Can change the implementation later!
• This is its beauty.
• Naturally the underlying data structure must make the specified
operations as efficient as possible.
• Sequential access? Perhaps a linked list.
• Random access? An array does if you know the index of the desired array
element.
T UE SD AY , 2 2 O CT O BE R 2 0 24 42
Sorted Lists

T UE SD AY , 2 2 O CT O BE R 2 0 24 43
Sorted list

• We need to store data in order


• Operations
• Insert
• DeleteSmallest, DeleteLargest
• Delete(key)
• Can used to replace Array
• Insertion speed is faster
• Size of the list can expand

T UE SD AY , 2 2 O CT O BE R 2 0 24 44
How would you do that

• Operations
• Insert
• DeleteSmallest
• DeleteLargest
• Delete(key)

T UE SD AY , 2 2 O CT O BE R 2 0 24 45
Insert data to sorted list

T UE SD AY , 2 2 O CT O BE R 2 0 24 46
Efficiency of sorted list

• Find/ Insertion / Deletion of arbitrary item: O(n)


• Find/ Insertion / Deletion of smallest/largest item: O(1)
➔ Useful for frequently access the minimum/maximum item
application (Priority queue)

T UE SD AY , 2 2 O CT O BE R 2 0 24 47
Application

• Sort an array - List Insertion Sort


• Insert each item of an array to a sorted list
• Get item from list and insert back to array
➔ Still O(n2)
• But
• Fewer copy/shift operation
• N*2 vs N2

T UE SD AY , 2 2 O CT O BE R 2 0 24 48
Some code

T UE SD AY , 2 2 O CT O BE R 2 0 24 49
Doubly linked lists

T UE SD AY , 2 2 O CT O BE R 2 0 24 50
Introduction

• Singly linked list: One way traversing


• current = current.next
➔need to traverse backward as well as forward through the list
➔doubly linked list

T UE SD AY , 2 2 O CT O BE R 2 0 24 51
Doubly linked list

T UE SD AY , 2 2 O CT O BE R 2 0 24 52
Doubly linked list

T UE SD AY , 2 2 O CT O BE R 2 0 24 53
Operations

• Insert • Delete
• InsertFirst • DeleteFirst
• InsertLast • DeleteLast
• InsertAfter • Delete(key)
• InsertBefore
• Display:
• DisplayForward
• DisplayBackward

T UE SD AY , 2 2 O CT O BE R 2 0 24 54
InsertFirst

T UE SD AY , 2 2 O CT O BE R 2 0 24 55
InsertFirst

T UE SD AY , 2 2 O CT O BE R 2 0 24 56
InsertLast
57

Adding new node at the end of Doubly Linked List


Data Structures and Algorithms in Java 5 7/2 3
Insert in the middle of list

T UE SD AY , 2 2 O CT O BE R 2 0 24 58
Delete an item

T UE SD AY , 2 2 O CT O BE R 2 0 24 59
Delete an item

• DeleteFirst?
• DeleteLast?

T UE SD AY , 2 2 O CT O BE R 2 0 24 60
Application

• Implement deque
• Queue that can insert and delete at either end
• Support bi-direction traversing

T UE SD AY , 2 2 O CT O BE R 2 0 24 61
Iterators

• Read “Data Structure and Algorithm”, Robert Lafore, page 231

T UE SD AY , 2 2 O CT O BE R 2 0 24 62
Lists in java.util - LinkedList class
boolean add(E o) Appends the specified element to the end of this list.
void addFirst(E o) Inserts the given element at the beginning of this list.
void addLast(E o) Appends the given element to the end of this list.
void clear() Removes all of the elements from this list.
E get(int index) Returns the element at the specified position in this list.
E getFirst() Returns the first element in this list.
E getLast() Returns the last element in this list.
E remove(int index) Removes the element at the specified position in
this list.
E removeFirst()Removes and returns the first element from this list.
E removeLast() Removes and returns the last element from this list.
int size() Returns the number of elements in this list.
Object[] toArray() Returns an array containing all of the elements in this list in the
correct order.

6 3/2 3
Lists in java.util
LinkedList class example
import java.util.*; class Main
class Node { {
String name; public static void main(String [] args)
int age; {
Node() {} LinkedList t = new LinkedList();

Node(String name1, int age1) { Node x; int n,i;


name=name1; age=age1;
} x = new Node("A01",25); t.add(x);

void set(String name1, int age1) { x = new Node("A02",23); t.add(x);


name=name1; age=age1;
} x = new Node("A03",21); t.add(x);

public String toString() { for(i=0;i<t.size();i++)


String s = name+" "+age; System.out.println(t.get(i));
return(s); }
} }
}

6 4/2 3
Lists in java.util - ArrayList class
boolean add(E o) Appends the specified element to the end of this list.
void add(int index, E o) Inserts the given element at the specified pos.
void clear() Removes all of the elements from this list.
E get(int index) Returns the element at the specified position in this list.
E remove(int index) Removes the element at the specified position in this
list.
int size() Returns the number of elements in this list.
void ensureCapacity(int minCapacity) Increases the capacity of this ArrayList
instance, if necessary, to ensure that it can hold at least the number of elements
specified by the minimum capacity argument.
void trimToSize() Trims the capacity of this ArrayList instance to be the list's
current size.
Object[] toArray() Returns an array containing all of the elements in this list in the
correct order.

6 5/2 3
Summary

• A linked list consists of one linkedList object and a number of Link


objects.
• The linkedList object contains a reference, often called first, to the first
link in the list.
• Each Link object contains data and a reference, often called next, to the
next link in the list.
• A next value of null signals the end of the list.
• Inserting an item at the beginning of a linked list involves changing the
new link’s next field to point to the old first link and changing first to point
to the new item.

T UE SD AY , 2 2 O CT O BE R 2 0 24 66
Summary

• Deleting an item at the beginning of a list involves setting first to


point to first.next.
• To traverse a linked list, you start at first and then go from link to link,
using each link’s next field to find the next link.
• A link with a specified key value can be found by traversing the list.
Once found, an item can be displayed, deleted, or operated on in
other ways.
• A new link can be inserted before or after a link with a specified key
value, following a traversal to find this link.
T UE SD AY , 2 2 O CT O BE R 2 0 24 67
Summary

• A double-ended list maintains a pointer to the last link in the list,


often called last, as well as to the first.
• A double-ended list allows insertion at the end of the list.
• An Abstract Data Type (ADT) is a data storage class considered
without reference to its implementation.
• Stacks and queues are ADTs. They can be implemented using either
arrays or linked lists.

T UE SD AY , 2 2 O CT O BE R 2 0 24 68
Summary

• In a sorted linked list, the links are arranged in order of ascending (or
sometimes descending) key value.
• Insertion in a sorted list takes O(N) time because the correct insertion
point must be found. Deletion of the smallest link takes O(1) time.
• In a doubly linked list, each link contains a reference to the previous
link as well as the next link.
• A doubly linked list permits backward traversal and deletion from the
end of the list.
T UE SD AY , 2 2 O CT O BE R 2 0 24 69
Practice

• DoublyLinkedApp.java
• Complete the functions:
• insertFirst
• insertLast
• deleteFirst
• deleteLast
• deleteKey
• displayForward
• displayBackward

T UE SD AY , 2 2 O CT O BE R 2 0 24 70
Vietnam National University of HCMC
International University
School of Computer Science and Engineering

THANK YOU

Dr Vi Chi Thanh - [email protected]


https://vichithanh.github.io

You might also like