Week 3: List: STIA2024 Data Structures & Algorithm Analysis
Week 3: List: STIA2024 Data Structures & Algorithm Analysis
Week 3: List: STIA2024 Data Structures & Algorithm Analysis
STIA2024
Data Structures & Algorithm
Analysis
1
Lecture Outlines
Contiguous List
Self-referential Classes
Dynamic Memory Allocation
Linked list
- Basic operations of linked list
2
Learning Objectives
• To describe the concept of linked list and
contiguous list,
• To describe the advantages and
disadvantages between contiguous and
linked list,
• To apply the use of dynamic and static
memory allocation in programming, and
• To apply those operations of linked list in
programming.
3
What is a Data Structure?
Disadvantages/ problems:
The size of list is fixed
A lot of operation of deletion and
insertion - updating the record will
involve shifting.
Waste memory when a space is not used
completely
10
Common Operations of Contiguous
List
1. Create a list
2. Find if the list is empty or full
3. Add a new element to the list
4. Remove an element from the list
5. Search an element on the list
Contiguous List - Create a List
Syntax :
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
myList
Contiguous List – Find if the list is
Empty?
Algorithm : Implementation:
Note: Must shift existing entries to provide space for a new data to be inserted
Except when adding as last entry
Contiguous List - Adding Data
If the list is empty
set new data as a first element
increase number of element (num)
Else if the list is full
display error message
else
find an index location of new data
set x=num
while x > search index
set an array element of [x-1] to be an array
element of [x]
decrease value of x
set new data at position of search index
increase value of num
Contiguous List - Adding Data
else{
for(int x=found; x<num;x++ )
myList[x]=myList[x+1];
num--;
}
}
}
Contiguous List - Searching Data
Set index=0
While index < number of elements (num)
if array element == target
return index
increase value of index
return -1 (if data not found)
Contiguous List - Searching Data
System.out.println(myList[index].toString( ));
}
Self- referential Classes
An Object that will refer to the others object from the
same classes
It is used when implementing the linked list’s data
structure
Data/ information is stored in a node.
Generally, every node has 2 data fields :
Info/ data - has related data
link/ pointer - pointing to the next node
Pointer is a “self referential classes” which point to
the other node
Info link Info link
25
Nodes
Dynamic Memory Allocation
Linked List -
Memory will be allocated when a space is required.
Memory will be released when a space is not required
anymore.
Contiguous List -
Memory cannot be released
Memory will be wasted when a space is not required
26
Linked List
A collection of list nodes where each node contains
info (data) and a link (reference) to the next node in the
linked list
Consists of several nodes (unlimited nodes)
To overcome the shifting problem.
Data link
One node
< constructor>
….
<Accessor and Mutator methods: getInfo, setInfo, getLink, setLink >
……
} // end Node
28
Linked List
Every list must have a pointer called “head” or “first
node” or ”front”.
If list is empty, head must be null.
If list is not empty, head must be pointed to the first
node and last node must be pointed to null.
// accessors
public Object getInfo()
{
return info;
}
public Node getLink()
{
return link;
}
// mutators
public void setInfo(Object newInfo)
{
info = newInfo;
}
public void setLink(Node newLink)
{
link = newLink;
}
}
31
Basic Operations of Linked List
1) Create a linked list
2) Inserting a node in linked list
a) First node
b) Last node
c) Between 2 nodes – based on searching required node
3) Removing a node from linked list
a) First node
b) Last node
c) Between 2 nodes – based on searching required node
4) Traversing the nodes in linked list
32
Create a Linked List
Pointer “head” must be initialized with null.
head
33
Inserting a First Node
Algo.
Create a new node
If list is empty
Set pointer “head” to new node
else
Set pointer “link” of new node to the first node
Set pointer “head” to the new node
Increase the number of nodes.
head
2
newNode
34
Inserting a First Node – Empty List
Node newNode = new Node(new Integer(8))
if (head == null)
head = newNode;
else {
newNode.setLink(head); // newNode.link = head
head = newNode;
}
count++;
head = newNode
X 8
head
newNode
8 Insert 8
head 35
Inserting a First Node – Non-empty
List
Node newNode = new Node(new Integer(7))
if (head == null)
head = newNode;
else {
newNode.setLink(head); // newNode.link = head
head = newNode;
}
count++;
X 8
head
head = newNode newNode.link = head
7 X
Insert 7
newNode
7 8 36
head
Inserting a Last Node
This process needs to be traversed from one node to
another node until reaching the last node.
We need a pointer called “current” to traverse nodes
Algo.
Create a new node
If list is empty
Set pointer “head” to the new node
else
set pointer “current” to the first node
Loop until pointer link of “current” not equal to null.
set pointer “current” to the next node //current = current.link
set pointer link of “current” to a new node
Increase the number of nodes.
37
Inserting a Last Node
Node newNode = new Node(new Integer(9))
if (head == null)
head = newNode;
else
{
Node current = head;
// traversing nodes
while (current.getLink() != null) // current.link != null
current = current.getLink(); // current = current.link
current.setLink(newNode); // current.link= newNode
}
count++;
38
Inserting a Last Node – Empty List
Node newNode = new Node(new Integer(8))
if (head == null)
head = newNode;
else
{
……..
}
head = newNode
X 8
head
newNode
8 Insert 8
head
39
Inserting a Last Node – Non-empty
List
Node newNode = new Node(new Integer(10))
if (head == null)
head = newNode;
else
{
Node current = head;
while (current.getLink() != null) // current.link != null
current = current.getLink(); // current = current.link
current.setLink(newNode); // current.link= newNode
}
40
Inserting a Last Node – Non-empty
List
Insert 10
current.link= newNode
8 9 X 10
head
current = head
newNode
current = current.link
current
8 9 10
head
41
Inserting Between Two Nodes
There are several ways to insert a new node
in between two nodes of linked list
Examples:
By position of node
By value via searching the required node
42
Inserting Between Two Nodes
Algo.
Create a new node
If list is empty
Set pointer “head” to new node
else
Set pointer “current” to the first node
Loop until current != null
if data of current node is not equal to target
set the pointer “current” to the next node
else if data of current node is equal to target
set pointer “link” of new node to pointer” link” of current node.
set link of pointer “current” to new node
break
If current is equal to null
“The target is not exist”
End loop
Increase the number of nodes.
43
Inserting Between Two Nodes
Node newNode = new Node(new Integer(5))
if(head==null)
head = newNode;
else{
Node current= head;
while (current != null){
if(current.getInfo()!= target)//current.info!=target
current = current.getLink(); // current = current.link
else if(current.getInfo() == target){ //current.info == target
newNode.setLink(current.getLink()); //newNode.link=current.link
current.setLink(newNode); // current.link = newNode
break;
}
if(current==null)
System.out.println(“The target is not exists”);
}
}
count++;
44
Inserting Between Two Nodes
Node newNode = new Node(new Integer(5))
if (head == null)
head = newNode;
else
{
Node current= head;
while (current != null){
if(current.getInfo()!= target)//current.info!=target
current = current.getLink(); // current = current.link
else if(current.getInfo() == target){ //current.info == target
newNode.setLink(current.getLink()); //newNode.link=current.link
current.setLink(newNode); // current.link = newNode
break; }
if(current==null)
System.out.println(“The target is not exists”);
}
}
count++;
45
Inserting Between Two Nodes
current.link = newNode
2 4 X 7
head
current= head
5 X
current newNode newNode.link = current.link
current = current.getLink();
Insert 5
2 4 5 7
head
46
Removing First Node
Algo.
If list is empty
Display an error message
Else
If only one node
Set pointer “head” to null
Else
Set pointer “head” to the next node
decrease the number of nodes.
2
head head
47
Removing First Node
head = head.getLink() // head = head.link
X 2 4 5 7
head
4 5 7
head
remove 2
48
Removing a Last Node
Before removing node, it must be checked whether the
list is empty or not.
This process needs to be traversed from one node to
another node until reaching last node.So, it needs
more times to reach last node.
Algo.
Set pointer “current” to the first node
Loop until current.link.link is not equal to null
Set pointer “current” to the next node
Set pointer “link” of current node to null.
Decrease the number of nodes.
49
Removing a Last Node
Node current = head;
// current.link.link != null
while (current.getLink().getLink() != null)
current = current.getLink();
current.setLink(null); // current.link = null
count--;
current.link().link() != null
2 4 5 X 7
head
current.link = null
current = current.getLink();
current remove 7
2 4 5
50
head
Removing Between Two Nodes
There are several ways to remove nodes in between
two nodes of linked list
Examples:
By position of node
By value via searching the required node
In this case, we use second technique
Must search the target first to delete that data
A certain node will be removed based on searching
required node.
51
Removing Between Two Nodes
Algo.
If list is empty
Msg “cannot be removed”
Else
if data/ info of first node is equal to target
set pointer “head” to second node
else
set pointer “before” to null
set pointer current to the first node
Loop until data/ info of current node is not equal to target AND
pointer “link” of current is not equal to null
set pointer before to pointer “current”
set pointer “current” to the next node
if data/info of current node is equal to target
set pointer link of “before” to pointer”link” of current
else
52
msg “target is not exists”
Removing Between Two Nodes
if (head == null)
System.out.println(“Cannot delete data”;
else if (head.getInfo() == target)
head = head.getLink();
else
{
Node before = null;
Node current= head;
// current.info != target
while ( (current.getInfo() != target) && (current != null) )
{
before = current;
current = current.getLink(); // current = current.link
}
if (current.getInfo() == target) // current.info == target
before.setLink(current.getLink()); // before.link = current.link
else
System.out.println(“The target is not exists”); 53
}
Inserting Between Two Nodes
if (head == null)
System.out.println(“Cannot delete data”);
else if (head.getInfo() == target)
head = head.getLink();
else
……..
head = head.getLink();
X 2 4 5 7
head
remove 2
4 5 7
head
54
Removing Between Two Nodes
if (head == null)
….
else if (head.getInfo() == target)
…..
else
{
Node before = null;
Node current= head;
// current.info != target
while((current.getInfo() != target) && (current != null) )
{
before=current;
current = current.getLink(); // current = current.link
}
if (current.getInfo() == target) // current.info == target
before.setLink(current.getLink());// before.link = current.link
else
System.out.println(“The target is not exists”); 55
}
Removing Between Two Nodes
X before.link = current.link
before
before = current
2 4 X 5 7
head
current = current.getLink();
current
2 4 7
head
remove 5
56
Traversing Nodes
Traversing is useful when
Displaying information for every node in the list
Searching an information in the list
To get number of nodes and etc……
Algo
Set pointer “current” to the first node
Loop until pointer “current” Is not equal to null
Set pointer “current “ to the next node
57
Traversing Nodes
System.out.print(“Data = “);
Node current = head;
While (current!= null)
{
System.out.println(current.getInfo());
current = current.getLink(); // current = current.link
}
2 4 5 7
head
current = current.getLink();
current
58
List in Java
List is one of the interfaces specified in the Java
Collection Framework
The JCF provides several types of collections,
such as sets, lists, queues and maps in the
form of interfaces.
A collection is a container object that represents a
group of objects, often referred to as elements
Java Collection Framework
hierarchy (partial).
Set and List are subinterfaces of Collection.
SortedSet TreeSet
Collection AbstractCollection
Vector Stack
List AbstractList
ArrayList
AbstractSequentialList LinkedList
Iterator
+hasNext(): boolean Returns true if this iterator has more elements to traverse
+next(): Object Returns the next element from this iterator
+remove(): void Removes the last element obtained using the next method
Removes all the elements from this collection
Iterator for List traversal
Iterator enables us to iterate over or traverse a
collection
Iterator is an interface (in java.util)
It contains only three methods:
hasNext()
next()
remove()
Most collections have an iterator() method that will
return an implementation of these methods
Iterator for List traversal
Iterator Approach:
Iterator it = list.iterator();
while (it.hasNext())
System.out.println(it.next());
List Traversal
List
+add(index: int, element: Object) : boolean Adds a new element at the specified index
+addAll(index: int, collection: Collection) : Adds all elements in the collection to this list at the
boolean specified index
+get(index: int) : Object Returns the element in this list at the specified index
+indexOf(element: Object) : int Returns the index of the first matching element
+lastIndexOf(element: Object) : int Returns the index of the last matching element
+listIterator() : ListIterator Returns the list iterator for the elements in this list
+listIterator(startIndex: int) : ListIterator Returns the iterator for the elements from startIndex
+remove(index: int) : int Removes the element at the specified index
+set(index: int, element: Object) : Object Sets the element at the specified index
+subList(fromIndex: int, toIndex: int) : List Returns a sublist from fromIndex to toIndex
List Iterator
A ListIterator has the usual Iterator methods:
hasNext(), next(), and remove(),
but it also has methods such as:
-hasPrevious()
-previous()
-add(obj)
that make it possible to move backwards in the
list and to add an item at the current position of
the iterator.
The List Iterator
Iterator
ListIterator
+add(o: Object) : void Adds the specified object to the list
+hasPrevious() : boolean Returns true if this list iterator has more elements
when traversing backward.
+nextIndex() : int Returns the index of the next element
+previousIndex() : int Returns the index of the previosu element
+previous() : Object Returns the previous element in this list iterator
+set(o: Object) : void Replaces the last element returned by the previous
or next method with the specified element
Java List classes
Several concrete classes implement the List
interface such as:
ArrayList
Vector
LinkedList
They are categorised based on the type of data
structures used to implement the lists:
- Array (ArrayList & Vector)
- Sequence of linked data or linked list
(LinkedList)
Using ArrayList Class
Vector
+addElement(o: Object): void Appends the element to the end of this vector
+capacity(): int Returns the current capacity of this vector
+copyInto(anArray: Object[]): void Copies the elements in this vector to the array
+elementAt(index: int): Object Returns the object at the specified index
+elements(): Enumeration Returns an emulation of this vector
+ensureCapacity(): void Increases the capacity of this vector
+firstElement(): Object Returns the first element in this vector
+insertElementAt(o: Object, index: int): void Inserts o to this vector at the specified index
+lastElement(): Object Returns the last element in this vector
+removeAllElements() : void Removes all the elements in this vector
+removeElement(o: Object) : boolean Removes the first matching element in this vector
+removeElementAt(index: int) : void Removes the element at the specified index
+setElementAt(o: Object, index: int) : void Sets a new element at the specified index
+setSize(newSize: int) : void Sets a new size in this vector
+trimToSize() : void Trims the capacity of this vector to its size
Using the Vector Class
List AbstractSequentialList
LinkedList
+addFirst(o: Object) : void Adds the object to the head of this list
+addLast(o: Object) : void Adds the object to the tail of this list
+getFirst() : Object Returns the first element from this list
+getLast() : Object Returns the last element from this list
+removeFirst() : Object Returns and removes the first element from this list
+removeLast() : Object Returns and removes the last element from this list
Using LinkedList Class
while (listItr.hasPrevious()) {
System.out.println(listItr.previous() + " ");
}
Using LinkedList Class
Output:
green
yellow
red
red
yellow
green
References
Data Structures and Abstractions with Java . Authors: Frank M.
Carrano & Walter Savitch . Chapter 5 and 6
Data Structures & Other Objects Using Java. Author: Michael Main
Chapter 4
78
Conclusion
Q & A Session
79
Exercise
If myList is an empty list, what is the output produced
after the following statements execute?
LinkedList myList = new LinkedList();
myList.add("alpha");
myList.add(0,"beta");
myList.add("gama");
myList.add(2,"delta");
myList.add("alpha");
myList.remove(1);
myList.remove("delta");
myList.remove(2);
for (Object element : myList)
System.out.print(element + " "); 80