Move forward a node in linked list

shabbir's Avatar author of Move forward a node in linked list
This is an article on Move forward a node in linked list in C.
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's Avatar, Join Date: Feb 2008
Go4Expert Member
i needed this thanks
programming girl's Avatar, Join Date: Apr 2008
Light Poster
wonderful !!