LinkedList
:
LinkedList
in Java:
LinkedList
:
LinkedList
can be created using:LinkedList<String> list = new LinkedList<>();
LinkedList
is empty β it has no nodes.
The head and tail both point to null
.
Head β null
, Tail β null
, Size = 0
add()
:list.add("A");
null
null
0
list.add("B");
list.add("C");
list.add("D");
"X"
between "B"
and "C"
: LinkedList
:
LinkedList
is traversed sequentially from head to tail using Iterator
or ListIterator
.
Iterator<String> itr = list.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
ArrayList
, elements are not accessed using indexes directly; instead, traversal follows node links.
LinkedList
is Good for:
ArrayList
.
LinkedList
is Not Good for:
get(int index)
):
next
and prev
), consuming more memory.
ArrayList
.
Operation | Performance | Complexity |
---|---|---|
Access by index (get) |
Slow | O(n) |
Update by index (set) |
Slow | O(n) |
Add at beginning/end |
Fast | O(1) |
Insert in middle |
Fast (if reference known) | O(1) for known node, otherwise O(n) |
Remove by node |
Fast (if reference known) | O(1) for known node, otherwise O(n) |
Search (contains) |
Slow | O(n) |
Iteration |
Slower | O(n), not cache-friendly |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.