Pages

Saturday, November 8, 2014

Traversing a Linked List

The word "traverse" means "to go or travel across or over".

Uses of traversal:-



  • If we want to modify each of the elements in the list then we need to travel across each element , there comes the need of traversal. 
e.g. LIST = 1, 2, 3, 4, 5....
        We want to add 0 to each of the element then we shall traverse the linked list.        After traversing the list will be LIST:- 10,20,30,40,50....


Program to traverse a linked  linked list :-




#include <stdio.h>


#include <stdlib.h>

/*www.TheTechmadness.in*/

int list[20];
int link[20];
int start;
void process(int);
void main()
{
    int ptr;
    list[0]=22;list[2]=5;list[3]=19;list[5]=87;list[7]=29;list[8]=79;
    list[9]=33;list[11]=2;list[13]=50;list[14]=8;list[16]=55;list[18]=99;

    link[0]=3;link[2]=13;link[3]=2;link[5]=8;link[7]=14;link[8]=9;link[9]=18;
    link[11]=16;link[13]=5;link[14]=-1;link[16]=0;link[18]=7;

    start=11;
    ptr=start;
    printf("initial list:\n");
    while(ptr!=-1)
    {
        printf("%d\t",list[ptr]);
        ptr=link[ptr];
    }
    ptr=start;
    while(ptr!=-1)
    {

        process(ptr);  //traversing list to apply process
        ptr=link[ptr];
    }
    ptr=start;
    printf("\n\nlist after traversal:\n");
    while(ptr!=-1)
    {

        printf("%d\t",list[ptr]);
        ptr=link[ptr];
    }
    getch();
}
void process(int p1)
{

    list[p1]=list[p1]*10;
}

Output:-

initial list:
2       55      22      19      5       50      87      79      33      99
29      8

list after traversal:
20      550     220     190     50      500     870     790     330     990
290     80



No comments:

Post a Comment