A linked list is one of the many data structures that Computer Science has developed to manage/organize information
The linked list is a dynamic structure, i.e., the number of elements in a linked list can increase and decrease in time
(In contrast, the array data structure is static, number of elements stays constant)
Symbolically:
Linked list element: +-----------------------+ | | | | <---- data part (variables that | | hold actually information | | that you want to store +-----------------------+ | | <---- linkage part (reference variable | | containing address of neighboring +-----------------------+ list elements
Symbolically:
A simple linked list: +--------+ -->+--------+ -->+--------+ | info1 | / | info2 | / | info3 | | | / | | / | | +--------+ / +--------+ / +--------+ | ref1 |- | ref2 |- | null | +--------+ +--------+ +--------+
Each linked list element is located somewhere in memory, and thus, each linked list element has a starting memory address
The linkage reference variables contains the address of the next linked list element
Example: the above linked list of 3 element would be linked together as follows:
We have to make some assumptions to do the example. The assumptions are: First element of linked is is located at address 8000 Second element of linked is is located at address 10000 Third element of linked is is located at address 9000 Memory: | | +---------------+ 8000 | info1 | Linked list element 1 +---------------+ | ref1=10000 |-------------------------------------+ +---------------+ | | | | +---------------+ | ....... | ....... | +---------------+ | 9000 | info3 | Linked list element 3 <----+ | +---------------+ | | | ref3=0 (null) | | | +---------------+ | | ....... | | ....... | | +---------------+ | | 10000 | info2 | Linked list element 2 | <-----+ +---------------+ | | ref2=9000 |-----------------------------+ +---------------+
That is why you need an extra variable usually called head that contains a reference (address) of the first element in the linked list:
Symbolically:
The user view of a linked list: head +--------+ +--------+ -->+--------+ -->+--------+ | |---->| info1 | / | info2 | / | info3 | +--------+ | | / | | / | | +--------+ / +--------+ / +--------+ | ref1 |- | ref2 |- | null | +--------+ +--------+ +--------+
This is what happens in reality:
Memory: +---------------+ head: | 8000 |-------------------------------+ +---------------+ | | | | ....... | ....... | +---------------+ | 8000 | info1 | Linked list element 1 <-----+ +---------------+ | ref1=10000 |-------------------------------------+ +---------------+ | | | | +---------------+ | ....... | ....... | +---------------+ | 9000 | info3 | Linked list element 3 <----+ | +---------------+ | | | ref3=0 (null) | | | +---------------+ | | ....... | | ....... | | +---------------+ | | 10000 | info2 | Linked list element 2 | <-----+ +---------------+ | | ref2=9000 |-----------------------------+ +---------------+