CIS-255 Home: http://www.c-jump.com/bcc/c255c/c255syllabus.htm
|
|
A linked list can grow and shrink while the program is running.
The program controls how linked list is built and managed.
Linked list permits insertion and removal of nodes at any point in the list.
As a result, the logical order of the linked nodes may be different from the order of objects in memory.
There are basically three design models to handle linked lists:
The C-style approach of using global functions and structs to hold data.
Using C++ node class with
private member variables
public member functions for data manipulation and list operations.
Node is a typical C++ class with access to data and interface to manipulate links between nodes.
A list class provides an interface to add and remove data from the list.
For example, STL list class implements doubly-linked list of "elements":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Since Node implementation is using pointers, a copy constructor is absolutely crucial to programmer's peace of mind!
class Node {
friend void print_list( Node const& head );
Node* pnext;
public:
int data;
// Constructor taking initial value:
Node( int value = 0 )
: pnext( NULL ), data( value )
{
}
// Copy constructor:
Node( Node const& other )
: pnext( NULL ), data( other.data )
{
}
};
|
|
Singly-linked list:
Doubly-linked list:
Circularly-linked list:
The first and the final nodes are linked together:
Traversal begins at any node and follows the list until reaching the original node.
Most useful when one object in a list needs to access all other objects in the list.
Disadvantage: complexity of iteration.
Linked lists are building blocks for many other data structures:
 
|
|
|
 
Linked lists have specific advantages over arrays:
Nodes can be inserted into linked list indefinitely;
Array will eventually fill up and needs to be resized.
(an expensive operation that may not even be possible if memory is fragmented.)
On the other hand,
arrays allow random access
linked lists allow only sequential access to elements.
(Singly-linked lists, in fact, can only be traversed in one direction.)
Singly-linked list:
Doubly-linked lists:
require more space per node
list operations are more expensive
easy sequential access to nodes in both directions
Should you always keep one pointer variable pointing to the head of a linked list?
Yes, if you have a Singly-linked list constructed from objects similar to Node:
No, if using Doubly-linked list or Circularly-linked:
Further reading: Wikipedia, Linked list