Why?
Data in Array is stored contiguously (in memory locations that are near each other), whereas in Linked list is stored non contiguously (could be near, could be far away from each other in memory).
Vs Array which you have to shift when add() or remove(), add() or remove() is constant for data in the middle of list because elements need not be shifted. The search for the position itself is not constant on average.
Insertion of new element
tmp = new ListNode();
tmp.element = x;
tmp.next = current.next;
current.next = tmp;
Removal of an element
Assume current is one position behind the element that we want to remove
current.next = current.next.next
How to count element in linked list?
- return integer count
- create listSize() implementation
public static int listSize (List theList)
{
int size = 0;
ListItr itr = new ListItr (theList);
for (itr.first(); itr.isInList(); itr.advance())
{
size++;
}
return size;
}
Standard
insert(x), remove(x), find(x)
Derived Methods
removeNext(), isInList()
Analisa Kompleksitas Running Time
insert next, prepend – O(1)
delete next, delete first – O(1)
find – O(n)
retrieve current position – O(1)
Adv
- growable
- linear time read, insert, delete
disadv
- new Node()
- one reference overhead for each and every node
Print linked list
- Loop without iterator
- Recursion without iterator
- Recursion
- with Iterator
More specific implementation of linked list.
- Sorted Linked List
- insert(x) method is different and not linear since it finds the correct position for the element first before inserting
- Could be implemented using inheritance of the previously defined linked list
- Doubly Linked List
- Node has two references (prev and next) instead of just next.
- Remove could be different
- if current.next and current.prev is not null
- current.prev.next = current.next
- current.next.prev = current.prev
- else if current.next = null
- current.prev.next = null
- current.prev = null
- else if current.prev = null
- current.next.prev = null
- current.next = null
- Circular Linked List
- Last node has reference to the first node
- could be implemented with or without header node.
- Insert
- 1 newNode = new DoublyLinkedListNode(x);
2 newNode.prev = current;
3 newNode.next = current.next;
4 newNode.prev.next = newNode;
5 newNode.next.prev = newNode;
6 current = newNode;
- 1 newNode = new DoublyLinkedListNode(x);
- deleteCurrent
- 1. current.prev.next = current.next;
2. current.next.prev = current.prev;
3. current = current.prev;
- 1. current.prev.next = current.next;