Linked list

  • Linked list:

    • a linear (single-way) linked data structure used to store information of identical format

  • Strength of the linked list:

    • The number of elements in the linked list is dynamic

      (Easily add or delete nodes from a linked list)

  • Property of a linked list:

    • The user only know the location of the first element of the linked list

    • The location information of the (i+1)th-element in the list is stored inside the ith-element of the list

    Therefore:

      • We must access the ith-element before we can access the (i+1)th-element

How is a linked list stored in the computer memory ?

  • Consider the following linked list:

    Remember that: memory locations are identified uniquely by their addresses

How is a linked list stored in the computer memory ?

  • Internally, this linked list is stored in the memory as follows:

    • head contains the address (reference) of the first Node object

    • Each next field contains the address (reference) of the subsequent Node object

A quick (short) refresher on linked list in C

A sample struct Node definition:

  struct Node
  {
     int          value;
     struct Node *next;   // A reference variable !
  }
 

 

A quick (short) refresher on linked list in C

C program used to traverse a linked list:

struct Node
{
   int          item;
   struct Node *next;
};

int main(int argc, char *argv[])
{
   struct Node *first = makeList(x); // Create a linked list

   struct Node *p;

   /* -----------------------------------
      List traversal algorithm in C
      ----------------------------------- */
   p = first;

   while ( p != NULL )
   {
      printf("%d ", p->item);
      p = p->next;  // Advances p to next node
   }
   printf("\n");
}   

DEMO:   /home/cs255001/demo/C/Linked-list/traverse.c

Summary:   How to access list objects in a linked list

(1) Start with head (a.k.a. first)

(2) Follow the location information in the next variables in the Node "objects":