Basic Linked List Operations
Successfully solving linked list problems requires a thorough understanding of how to operate on linked lists. This includes tracking the head element so that the list doesn’t get lost, traversing the list, and inserting and deleting list elements. These operations are much more straightforward with a doubly linked list, so we focus on the pitfalls of implementing these operations for singly linked lists.
Tracking the Head Element
The head element of a singly linked list must always be tracked; otherwise, the list will be lost — either garbage collected or leaked, depending on the language. This means that the pointer or reference to the head of the list must be updated when a new element is inserted ahead of the first element or when the existing first element is removed from the list.
Tracking the head element becomes a problem when you alter the list inside a function or method, because the caller must be made aware of the new head element. For example, the following Java code is incorrect because it fails to update the reference to the head of the list:
public void insertInFront( ListElement<Integer> list, int data ){
ListElement<Integer> l = new ListElement<Integer>( data );
l.setNext( list );
}
The correct solution is to return the new head element from the method:
public ListElement<Integer> insertInFront( ListElement<Integer> list, int data ){
ListElement<Integer> l = new ListElement<Integer>( data );
l.setNext( list );
return l;
}
The caller ...
Get Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.