Lecture04 Arrays Singly Linked Lists
Lecture04 Arrays Singly Linked Lists
YoungMin Kwon
Lists
List
A linear sequence of elements
Implementations
Arrays
Singly linked lists
Circularly linked lists
Doubly linked lists
Arrays
Example 1
Storing game entries for a video
game in an array
Information to store
Name of the player
Score of the game
Add a reference to
Kim
Removing an Entry
Removing an entry at index i from a
Scoreboard
Node
Has a reference to its element object
Has a reference to the next node
Singly Linked Lists
Linear structure
No one is referencing
this node
⇒it will be garbage
collected
Removing an Element
Removing a node from the tail
Unfortunately, it is not easy to remove a node
from the tail
Need to find the node before the tail
Need to scan from the head to the node before
the tail
public SinglyLinkedList() {}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public E first() {
return isEmpty() ? null : head.getElement();
}
public E last() {
return isEmpty() ? null : tail.getElement();
}
//return value
E ret = head.getElement();
return ret;
}
public E removeLast() {
//TODO: implement this method
}
private static void onFalseThrow(boolean b) {
if(!b)
throw new RuntimeException("Error: unexpected");
}
list.addLast(2);
list.addLast(3);
list.addLast(4);
list.addFirst(1);
onFalseThrow(list.removeLast() == 4);
onFalseThrow(list.removeLast() == 3);
onFalseThrow(list.removeFirst() == 1);
onFalseThrow(list.removeLast() == 2);
System.out.println("Success!");
}
}