Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)

 shabbir 27Aug2006 17:53

Move forward a node in Linked List

Relocating a node in the linked list is one of major operation and I have tried to simulate one type of movement. i.e. moving forward.
Code: C

`node* MoveForward(node *current){    int rno;                         /* Roll number for moving of node */    int n;                           /* Number of nodes to skip */    int i;                           /* Loop variable */    int t;                           /* Total number of nodes */    node *tmp;                       /* Temporary copy of current */    node *temp1,*temp2,*temp3;       /* Temporary variable */    /** Interchanging temp1 and temp2 with temperorary node temp3 **/    /** temp3 stores the address of temp1->next **/    node *prev1,*prev2;    /** prev1 is previous to temp1 and prev2 is previous to temp2 **/    t=number(current);    if(t<=2)    {        printf("\nFirst node cannot be moved forward by one position.\n");        printf("\nYou need to swap them.\n");        return(current);    }    printf("\nEnter roll number whose node you want to move forward\n");    scanf("%d",&rno);    printf("\nEnter the number of nodes to skip\n");    scanf("%d",&n);    tmp=current;    if(current->roll_no==rno)    {        temp1=current;        temp3=current->next;        temp2=current->next;        for(i=0;i!=n;i++)        {            prev2=temp2;            temp2=temp2->next;        }        temp1->next=temp2->next;        prev2->next=temp1;        temp2->next=temp3;        current=temp2;        return(current);    }    else    {        while(tmp->next!=NULL)        {            prev1=tmp;            tmp=tmp->next;            if(tmp->roll_no==rno)            {                temp1=tmp;                temp3=tmp->next;                temp2=tmp->next;                for(i=0;i!=n;i++)                {                    prev2=temp2;                    temp2=temp2->next;                }                break;            }        }        prev1->next=temp2;        prev2->next=temp1;        temp1->next=temp2->next;        temp2->next=temp3;        return(current);    }}`

You should be calling the above function as follows
Code: C

`head=MoveForward(head); // Head is the first node of the linked list  `

And last but not the least you should also know how the structure of the linked list is defined.
Code: C

`struct list{    int roll_no;          /* Storing roll number of a node */    char name[N];         /* Storing name of node */    float marks;          /* Storing marks of a node */    struct list *next;    /* Storing next address */};/*****  Redefining struct list as node  *****/typedef struct list node;`

 rashida.par 13Mar2008 15:37

Re: Move forward a node in linked list

i needed this thanks

 programming girl 25Apr2008 23:52

Re: Move forward a node in linked list

wonderful !!

 All times are GMT +5.5. The time now is 21:16.