Display Linked List from First to Last



Display Singly Linked List from First to Last

In the last chapter we have learn’t about traversing the linked list. In this chapter we will be printing the content of the linked list from start to last.

Steps for Displaying the Linked List :

  1. In order to write the program for display, We must create a linked list using create(). Then and then only we can traverse through the linked list.
  2. Traversal Starts from Very First node. We cannot modify the address stored inside global variable “start” thus we have to declare one temporary variable -“temp” of type node.
  3. In order to traverse from start to end you should assign Address of Starting node in Pointer variable i.e temp
struct node *temp;  //Declare temp
temp = start;       //Assign Starting Address to temp

Now we are checking the value of pointer (i.e temp). If the temp is NULL then we can say that last node is reached.

while(temp!=NULL)
    {
    printf("%d",temp->data);
    temp=temp->next;
    }

See below dry run to understand the complete code and consider the linked list shown in the above figure -

Control Position Printed Value temp points to
Before Going into Loop - Starting Node
Iteration 1 1 Node with data = 3
Iteration 2 3 Node with data = 5
Iteration 3 5 Node with data = 7
Iteration 4 7 NULL
Iteration 5(False Condition) - -

Complete Display Function :

void display()
{
    struct node *temp;
    temp=start;
    while(temp!=NULL)
    {
    printf("%d",temp->data);
    temp=temp->next;
    }
}