Traversing through LL



Traversing through Singly Linked List (SLL) :

In the previous chapter we have learnt about the Creation of Singly Linked List. In this chapter, we will see how to traverse through Singly Linked List using C Programming.

1. Introduction :

Consider the Singly Linked list node structure. Traversing linked list means visiting each and every node of the Singly linked list. Following steps are involved while traversing the singly linked list –

  1. Firstly move to the first node
  2. Fetch the data from the node and perform the operations such as arithmetic operation or any operation depending on data type.
  3. After performing operation, advance pointer to next node and perform all above steps on Visited node.

2. Node Structure and Program Declaration :

struct node {
  int data;
  struct node *next;
}*start=NULL;

and the function definition for traversing linked list is –

struct node *temp = start; //Move to First Node

do {

    // Do Your Operation
    // Statement ...1
    // Statement ...2
    // Statement ...3
    // Statement ...n

    temp = temp->next; //Move Pointer to Next Node

}while(temp!=NULL);

3. Explanation of Traversing Linked List :

We know that, In order to traverse linked list, We need to visit first node and then visiting nodes one by one until the last node is reached.

temp = start; //Move to First Node
do {
    // Do Your Operation
    // Statement ...1
    // Statement ...2
    // Statement ...3
    // Statement ...n
    temp = temp->next; //Move Pointer to Next Node

}while(temp!=NULL);

Explanation :

Initially

temp = start;
  1. Store Address of Starting node into “temp” , Print data stored in the node “temp“. ## Refer : Different Syntax and Terms in Linked List
  2. Once Data stored in the temp is printed, move pointer to the next location so that “temp” will contain address of 2nd node.

[box]

Special Note :

In Singly Linked List Program , do not change start index un-necessarily because we must have something that can store address of Head node

[/box]