The code below swaps two nodes in the linked list. The swap operation can be helpful in sorting a linked list and so its very important how to swap the nodes of linked list.

Swapping in normal arrays is swap of the data but in linked list its the pointers change and so there is just change in the index of the linked list where the node will remain.

You need to call the function as below.

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

Swapping in normal arrays is swap of the data but in linked list its the pointers change and so there is just change in the index of the linked list where the node will remain.

Code: C

node* swap(node *current)

{

int rno; /* Roll number for swaping node*/

int t; /* Total number of nodes */

node *temp; /* Temporary copy of current */

node *tmp; /* Temporary variable */

t=number(current);

if(t<=1)

{

printf("\nYou cannot swap the only node\n");

return(current);

}

printf("\nEnter roll number whose node you want to swap with the next\n");

scanf("%d",&rno);

temp=current;

if(current->roll_no==rno)

{

tmp=current->next;

current->next=current->next->next;

tmp->next=current;

current=tmp;

return(current);

}

else

{

while(temp->next->next!=NULL)

{

if(temp->next->roll_no==rno)

{

tmp=temp->next->next;

temp->next->next=temp->next->next->next;

tmp->next=temp->next;

temp->next=tmp;

break;

}

temp=temp->next;

}

return(current);

}

}

Code: C

head=swap(head); // head is the first node of the linked list

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;

- Linked List
- Basic operations in Linked List
- Insert a node in a Linked List
- Swap two nodes of a Linked List
- Move forward a node in Linked List
- Double Linked List
- Circular Linked List
- Double Circular Linked List
- Stack Implementation using Linked List
- Queue implementation through Linked List
- Priority Queue implementation using Linked List