Linked Lists Flashcards
What are some problems that arrays/arraylists have that linked lists solve?
- adding or deleting elements from the middle or the front requires other elements to be shifted, which consumes resources
- adding another element when full requires a complete re-build of the array into a new one
What is a Node?
An object that contains some data (or a reference to it) and a reference to the next Node in the list (or null if there isn’t one)
Why do Nodes make an exception to the “instance variables must be private” rule?
Because Nodes are useless without lists, so you can control all use of nodes by simply keeping them private to the linked list. This means that you must never return a node from a method in a linked list
What are some cases you must consider for an add function of a linked list?
- if the list is empty
- if the requested position does not exist
- if the position is 0
Compare adding with an array to adding with a linked list
array:
- must “shuffle” all elements after (loop needed)
- can access the desired position directly
- might get full and require expansion of the array
- easiest to add to the end
list:
- no need to shuffle; very quick insertion
- must follow the chain through all previous elements to find
the right position (loop needed)
- can’t get full (unless you completely run out of memory)
- easiest to add to the beginning
What are some cases to consider when removing an item from a linked list?
- if the list is empty
- if the first node is the one requested to remove
- if the item doesn’t exist
What searching algorithm should be used on a linked list?
Binary search is impossible on a linked list, so for now, use linear search