# Move forward a node in Linked List

Discussion in 'C' started by shabbir, Aug 27, 2006.

1. ### shabbirAdministratorStaff Member

Joined:
Jul 12, 2004
Messages:
15,358
Likes Received:
383
Trophy Points:
83
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:
```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:
```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:
```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;
```

2. ### rashida.parNew Member

Joined:
Feb 14, 2008
Messages:
21
Likes Received:
1
Trophy Points:
0
i needed this thanks

3. ### programming girlNew Member

Joined:
Apr 24, 2008
Messages:
8
Likes Received:
0
Trophy Points:
0
wonderful !!