02 - Linked List
02 - Linked List
Algorithms
2
Policies for students
■These contents are only used for students
PERSONALLY.
■Students are NOT allowed to modify or
deliver these contents to anywhere or anyone
for any purpose.
3
Recording of modifications
■Course website address is changed to
http://sakai.it.tdt.edu.vn
■Slides “Practice Exercises” are eliminated.
■Course codes cs1010, cs1020, cs2010 are
placed by 501042, 501043, 502043
respectively.
4
Objectives
• Able to define a List ADT
1
Motivation
1. Use of a
Motivation
❑ List is one of the most basic types of data collection
▪ For example, list of groceries, list of modules, list of friends,
List
etc.
▪ In general, we keep items of the same type (class) in one list
❑ Typical Operations on a data collection
▪ Add data
▪ Remove data
▪ Query data
▪ The details of the operations vary from application to
application. The overall theme is the management of data
To be discussed
in section 2.
Contractual
obligations: Java Arrays
List ADT
1.Create empty
list
2.Determine … Linked Lists
3.Add an item
To be discussed
… in section 3:
Basic Linked List
ADT Implementations
Fixed-size list
2. List Implementation: Array
(1/9)
❑ This is a straight-forward approach
❑ Use Java array of a sequence of n elements
num_nodes arr : array[0..m] of locations
0 1 2 n-1 m
Legend:
implements
8 a0 a1 a2 a3 a4 a5 a6 a7
8 a0 a1 a2 a3 a4 a5 a6 a7
◈
[501043 Lecture 8: List ADT & Linked Lists]
21
2. Analysis of Array Impln of
List (8/9)
■ Question: Time Efficiency?
❑ Retrieval: getFirst()
■ Always fast with 1 read operation
❑ Insertion: addFirst(E item)
■ Shifting of all n items – bad!
❑ Insertion: add(int index, E item)
■ Inserting into the specified position (not shown in ListUsingArray.java)
❑ Best case: No shifting of items (add to the last place)
❑ Worst case: Shifting of all items (add to the first place)
❑ Deletion: removeFirst(E item)
■ Shifting of all n items – bad!
❑ Deletion: remove(int index)
■ Delete the item at the specified position (not shown in
ListUsingArray.java)
❑ Best case: No shifting of items (delete the last item)
❑ Worst case: Shifting of all items (delete the first item)
[501043 Lecture 8: List ADT & Linked Lists]
22
2. Analysis of Array Impln of
List (9/9)
■ Question: What is the Space Efficiency?
❑ Size of array collection limited by MAXSIZE
❑ Problems
■ We don’t always know the maximum size ahead of time
■ If MAXSIZE is too liberal, unused space is wasted
■ If MAXSIZE is too conservative, easy to run out of space
Variable-size list
3.1 List Implementation: Linked
List (1/3)
❑ Recap when using an array...
❑ X, A, B are elements of an array
Unused spaces
❑ Y is new element to be added
X A B
I want to add
Y after A. I want to
remove A.
Y
X A B
I want to
add Y after
Y
A.
?
X A B
I want to
Node A becomes a
remove A
garbage. To be removed
….
during garbage collection.
String
❑ An instance (object) of a class only comes into existence
(constructed) when the new operator is applied
❑ A reference variable only contains a reference or pointer to an object.
[501043 Lecture 8: List ADT & Linked Lists]
29
3.2 Linked List Approach (3/4)
❑ Recap: Object References (2/2)
❑ Look at it in more details:
w = y; Integer
if (w == y)
System.out.println("2. w == y");
❑ Output:
◈
[501043 Lecture 8: List ADT & Linked Lists]
30
3.2 Linked List Approach (4/4)
❑ Quiz: Which is the right representation of e?
class Employee {
private String Employee e = new Employee("Alan", 2000);
name;
private int
salary;
// etc.
} (A) (B)
e e
Alan 2000 Alan 2000
(C) e (D) e
2000
◈
[501043 Lecture 8: List ADT & Linked Lists]
31
3.3 ListNode (using generic)
ListNode.java
class ListNode <E> {
/* data attributes */ element next
private E element;
private ListNode <E> next;
/* constructors */
public ListNode(E item) { this(item, null); }
/*{
Element = item;
Next = null;
}*/
public ListNode(E item, ListNode <E> n) {
element = item;
Mark this slide – You may need to refer to it later
next = n;
} when we study the different variants of linked list.
/* get the next ListNode */
public ListNode <E> getNext() { return next; }
/* get the element of the ListNode */
public E getElement() { return element; }
/* set the next reference */
public void setNext(ListNode <E> n) { next = n };
}[501043 Lecture 8: List ADT & Linked Lists] 32
3.4 Forming a Linked List (1/3)
❑ For a sequence of 4 items < a0, a1, a2, a3 >
hea
d represents null
a0 a1 a2 a3
a0 a1 a2 a3
[501043 Lecture 8: List ADT & Linked Lists]
34
3.4 Forming a Linked List (3/3)
❑ Alternatively we can form the linked list as follows:
❑ For a sequence of 4 items < a0, a1, a2, a3 >, we can build as follows:
a0 a1 a2 a3
num_nodes++;
}
0 item head
num_nodes
head
num_nodes
0 99 1
0
1 2
◈
[501043 Lecture 8: List ADT & Linked Lists]
38
3.5 Basic Linked List (4/7)
■ The removeFirst() method
Case Before: list After: list.removeFirst()
0 item head num_nodes
0 can’t remove
System.out.println("Testing removal");
list.removeFirst();
list.print();
if (list.contains("aaa"))
list.addFirst("xxxx");
list.print();
}
}
◈
[501043 Lecture 8: List ADT & Linked Lists]
41
3.5 Test Basic Linked List #2
(7/7)
■ Example use #2
TestBasicLinkedList2.java
import java.util.*;
list.addFirst(34);
list.addFirst(12);
list.addFirst(9);
list.print();
System.out.println("Testing removal");
list.removeFirst();
list.print();
}
}
◈
[501043 Lecture 8: List ADT & Linked Lists]
42
4 More Linked Lists
+ setNext(ListNode <<interface>>
s-
EnhancedListInterface
a
<E> curr)
ts
en
m + isEmpty()
ple + size()
im
+ getFirst()
TailedLinkedList + contains(E item)
+ addFirst(E item)
+ removeFirst()
- head
+ print()
- tail + getHead()
- num_nodes + addAfter(ListNode <E> curr, E
item)
+ removeAfter(ListNode <E> curr)
+ remove( E item)
tem
hea p a
0
d
num_nodes
4
3 a0 a1 a2 a3
}
}
item
pre curr a2
v
hea
d
num_nodes
4
3 a0 a1 a2 a3
System.out.println();
System.out.println("Part 2");
ListNode <String> current = list.getHead();
list.addAfter(current, "xxx");
list.addAfter(current, "yyy");
list.print();
◈
[501043 Lecture 8: List ADT & Linked Lists]
54
4.1 Test Enhanced Linked List
(11/11) TestEnhancedLinkedList.java
// (continue from previous slide)
System.out.println();
System.out.println("Part 3");
current = list.getHead();
if (current != null) {
current = current.getNext();
list.removeAfter(current);
}
list.print();
System.out.println();
System.out.println("Part 4");
list.removeAfter(null);
list.print();
}
}
◈
[501043 Lecture 8: List ADT & Linked Lists]
55
4. Linked Lists: Variants
OVERVIEW!
BasicLinkedList implements <<interface>>
ListInterface
- head
- num_nodes
s -a + isEmpty()
ha + size()
ListNode + getFirst()
+ contains(E item)
- element has-a im + addFirst(E item)
EnhancedLinkedList ple
- next + removeFirst()
m
en + print()
+ getNext() - head ts
+ getElement() - num_nodes
ha
+ setNext(ListNode <<interface>>
s-
EnhancedListInterface
a
<E> curr)
ts
en
m + isEmpty()
ple + size()
im
+ getFirst()
TailedLinkedList + contains(E item)
+ addFirst(E item)
+ removeFirst()
- head
+ print()
- tail + getHead()
- num_nodes + addAfter(ListNode <E> curr, E
item)
+ removeAfter(ListNode <E> curr)
+ remove( E item)
tai
hea l
d
num_nodes
4 a0 a1 a2 a3
a b … g y y
New node New node
… p q … … p q
y y
■ Case 2A ■ Case 2B
❑ current == null; tail != null ❑ current == null; tail == null
head current head current
tail
a b …
y
y New node
New node
System.out.println("Part 1");
list.addFirst("aaa");
list.addFirst("bbb");
list.addFirst("ccc");
list.print();
System.out.println("Part 2");
list.addLast("xxx");
list.print();
System.out.println("Part 3");
list.removeAfter(null);
list.print();
}
}
◈
[501043 Lecture 8: List ADT & Linked Lists]
66
4. Linked Lists: Variants
OVERVIEW!
BasicLinkedList implements <<interface>>
ListInterface
- head
- num_nodes
s -a + isEmpty()
ha + size()
ListNode + getFirst()
+ contains(E item)
- element has-a im + addFirst(E item)
EnhancedLinkedList ple
- next + removeFirst()
m
en + print()
+ getNext() - head ts
+ getElement() - num_nodes
ha
+ setNext(ListNode <<interface>>
s-
EnhancedListInterface
a
<E> curr)
ts
en
m + isEmpty()
ple + size()
im
+ getFirst()
Difficulty: (Boundary cases) + contains(E item)
TailedLinkedList
Take care of all cases of update + addFirst(E item)
0 element - head
+ removeFirst()
1 element + print()
- tail + getHead()
2 elements - num_nodes + addAfter(ListNode <E> curr, E
3 or more elements, etc. item)
+ removeAfter(ListNode <E> curr)
+ remove( E item)
tai
hea l
d
num_nodes
4 a0 a1 a2 a3
prev next
x2
node
private E element;
private DListNode <E> prev;
private DListNode <E> next;
/* constructors */
public DListNode(E item) { this(item, null, null); }
public DListNode(E item, DListNode <E> p, DListNode <E> n)
{
element = item; prev = p; next = n;
}
/* get the prev DListNode */
public DListNode <E> getPrev() { return this.prev; }
/* get the next DListNode */
public DListNode <E> getNext() { return this.next; }
/* get the element of the ListNode */
public E getElement() { return this.element; }
/* set the prev reference */
public void setPrev(DListNode <E> p) { prev = p };
/* set the next reference */
public void setNext(DListNode <E> n) { next = n };
}[501043 Lecture 8: List ADT & Linked Lists]
71
5.2 Doubly Linked List (3/3)
■ An example of a doubly linked list
hea tai
d l
num_nodes
4 x1 x2 x3 x4
◈
[501043 Lecture 8: List ADT & Linked Lists]
79
Why “reinvent the wheel”?
■ In a data structures course, students are often
asked to implement well-known data structures.
■ A question we sometimes hear from students:
“Since there is the API, why do we need to learn to
write our own code to implement a data structure
like linked list?”
■ Writing the code allows you to gain an indepth
understanding of the data structures and their
operations
■ The understanding will allow you to appreciate their
complexity analysis (to be covered later) and use
the API effectively
[501043 Lecture 8: List ADT & Linked Lists]
80
7 Summary (1/2)
■We learn to create our own data structure
❑ In creating our own data structure, we face 3
difficulties:
1. Re-use of codes (inheritance confusion)
2. Manipulation of pointers/references (The sequence of
statements is important! With the wrong sequence, the
result will be wrong.)
3. Careful with all the boundary cases
❑ Drawings are very helpful in understanding the cases
(point 3), which then can help in knowing what can be
used/manipulated (points 1 and 2)