Professional Documents
Culture Documents
Session 5 part 2
Linked list in java
Another important type of a linked list is called a circular linked list where last node of
the list points back to the first node (or the head) of the list.
The Structure of Linked Lists
To understand the inefficiency of arrays and the need for a more efficient data structure,
imagine a program that maintains a sequence of employee names.
If an employee leaves the company, the name must be removed.
In an array, the hole in the sequence needs to be closed up by moving all objects that come
after it
Conversely, suppose an employee is added in the middle of the sequence.
Then all names following the new hire must be moved toward the end.
Moving a large number of elements can involve a substantial amount of processing time.
A linked list structure avoids this movement.
The Structure of Linked Lists
.
The Structure of Linked Lists
When you insert a new node into a linked list, only the neighboring node references need
to be updated
The same is true when you remove a node.
What’s the catch?
Linked lists allow efficient insertion and removal, but element access can be inefficient. .
Working with Linked Lists
List Iterators
iterator.next();
The next method throws a NoSuchElementException if you are already past the end of the
list.
You should always call the iterator’s hasNext method before calling next—it returns true if
there is a next element.
if (iterator.hasNext()) {
iterator.next();
}
Methods of the Iterator and ListIterator
Interfaces
Methods of the Iterator and ListIterator
Interfaces
The nodes of the LinkedList class store two links: one to the next element and one to the
previous one.
Such a list is called a doubly-linked list.
You can use the previous and hasPrevious methods of the ListIterator interface to move the
iterator position backward.
The add method adds an object after the iterator, then moves the iterator position past the
new element. iterator.add("Juliet");
You can visualize insertion to be like typing text in a word processor.
Each character is inserted after the cursor, then the cursor moves past the inserted character
Methods of the Iterator and ListIterator
Interfaces
The remove method removes the object that was returned by the last call to next or
previous.
For example, this loop removes all names that fulfill a certain condition:
while (iterator.hasNext()) {
String name = iterator.next();
if (condition is fulfilled for name) {
iterator.remove(); }
}
Linked list example
iterator.next();
}
Task 1
Suppose the list letters contains elements "A", "B", "C", and "D".
Draw the contents of the list and the iterator position for the following operations:
ListIterator iter = letters.iterator();
iter.next();
iter.next();
iter.remove();
iter.next();
iter.add("E");
iter.next();
iter.add("F");
Task 2
Write a loop that removes all strings with length less than four from a linked list of strings
called words.