Some generic "structures" when discussing linked lists:
struct Node
{
Node *next; // all node structs have this
Node *prev; // some node structs have this (double)
Data data; // the payload
};
Node *NewNode(void)
{
Node *p = new Node;
p->next = NULL;
p->prev = NULL; // depending on single/double linked list
return p;
}
Node *FreeNode(Node *node)
{
// possibly validate the node
delete node;
}
Some common operations with linked lists:
Let's follow an example of a singly-linked list. (There is only one Node * in the struct pointing to the next node.)Node *p1 = NewNode(); // create a new node, possibly initialized FreeNode(p1); // freeing a node, possibly returning to free store Node *head = p1; // always points to first node (NULL if empty list) Node *tail = p1; // always points to last node (NULL if empty list) Node *p2 = NewNode(); // create new node tail->next = p2; // add to end tail = tail->next; // update tail Node *p3 = NewNode(); // create new node p3->next = head; // add to front head = p3; // update head
We can allocate 3 nodes:
A diagram would look like this:Node *n1 = NewNode(); Node *n2 = NewNode(); Node *n3 = NewNode();
Then, we can "hook" up the nodes:
Resulting in this picture:n1->next = n2; n2->next = n3; Node *head = n1;
Node *head = NULL;
for (int i = 0; i < 3; i++)
{
Node *temp = NewNode();
temp->next = head;
head = temp;
}
The picture below shows the structure after one iteration of the for loop:
A second iteration then produces this:
And the third one results in this:
This is our new node to be added:
Node *node = NewNode();
node->next = head; head = node;
if (head == NULL)
head = node;
else
{
Node *t = head;
while (t->next)
t = t->next;
t->next = node;
}
node->next = given->next; given->next = node;
Node *t = head;
int count = 0;
while (count < index)
{
t = t->next;
count++;
}
node->next = t->next;
t->next = node;
Same as inserting after (K - 1). If K = 0 (head), just use InsertAtFront routine.
head = head->next;
if (head->next == NULL)
head = NULL;
else
{
Node *t = head;
Node *prev = NULL;
while (t->next)
{
prev = t;
t = t->next;
}
prev->next = NULL;
}
if (node == head)
head = head->next;
else
{
Node *prev, *t = head;
while (t != node)
{
prev = t;
t = t->next;
}
prev->next = t->next;
}
given->next = given->next->next;
if (index == 0)
head = head->next;
else
{
Node *prev, *t = head;
int count = 0;
while (count < index)
{
prev = t;
t = t->next;
count++;
}
prev->next = t->next;
}
The corresponding classic code for a linked list:// assume we have some array[SIZE] for (int i = 0; i < SIZE; i++) DoSomething(array[i]);
// assume we have a list
Node *t = head;
while (t)
{
DoSomething(t);
t = t->next;
}