Linked Lists

Linked Lists vs. Arrays

Linked Lists What is a Linked List? Operations on Linked Lists Linked List ADT

Useful Pointers

Creating and Deleting Nodes Why not do away with arrays and use linked lists for all lists?

Step-by-Step Example

The code below refers to pictures labelled A - G.
Pictures A - E are here.
Pictures F and G are here.

struct Node
{
  int data;
  Node* link;
};

void main(void)
{
    // Picture A
  Node* head;                  //  1
  Node* currPtr;               //  2
  Node* newNodePtr;            //  3

    // first node (Picture B)
  newNodePtr = new Node;       //  4
  newNodePtr->data = 3;        //  5
  newNodePtr->link = NULL;     //  6

    // Picture C
  head = newNodePtr;           //  7
  currPtr = newNodePtr;        //  8 

    // second node (Picture D)
  newNodePtr = new Node;       //  9
  newNodePtr->data = 6;        // 10
  newNodePtr->link = NULL;     // 11

    // Picture E
  currPtr->link = newNodePtr;  // 12
  currPtr = newNodePtr;        // 13

    // third node (Picture F)
  newNodePtr = new Node;       // 14
  newNodePtr->data = 9;        // 15
  newNodePtr->link = NULL;     // 16

    // Picture G
  currPtr->link = newNodePtr;  // 17
  currPtr = newNodePtr;        // 18
}
Example Using a Loop
struct Node
{
  int data;
  Node* link;
};


void main(void)
{
  Node* head;           // 1
  Node* currPtr;        // 2
  Node* newNodePtr;     // 3

  head = new Node;      // 4
  head->data = 3;       // 5
  currPtr = head;       // 6

  for (int i = 2; i <= 3; i++)
  {
    newNodePtr = new Node;     
    newNodePtr->data = i * 3;  
    newNodePtr->link = NULL;   
    
    currPtr->link = newNodePtr; 
    currPtr = newNodePtr;           
  }
}
Comments:
Inserting at the Head of the List

Sometimes you want to add at the head (front) of the list rather than at the tail (end). Notice that there is less code because we don't need a pointer to the end of the list:

void main(void)
{
  Node* head;           // 1
  Node* newNodePtr;     // 2

  head = new Node;      // 3
  head->data = 3;       // 4
  head->link = NULL;    // 5

  for (int i = 2; i <= 3; i++)
  {
    newNodePtr = new Node;    // create new Node on heap     
    newNodePtr->data = i * 3; // set the data in the node
    newNodePtr->link = head;  // set next node to the head
      
    head = newNodePtr;        // make this Node the new head
  }
}
This will remove a node from the head:
if (head != NULL)         
{
  Node* old_head = head;  // save pointer to head
  head = head->link;      // point head to next node
  delete old_head;        // delete old head node
}
What data structure might this be useful for?

Back to Outline