# Interchange the two adjacent nodes in a given circular linked list | C program

Here, we are going to learn how to interchange the two adjacent nodes in a given circular linked list using C program?
Submitted by Piyas Mukherjee, on January 31, 2019

Algorithm:

Function: largest_DLL()

Input: A singly linked list whose address of the first node is stored in a pointer say head and the node we have to exchange with its next node.

Output: The singly linked list with interchanged node

Data structure used: Circular linked list where each node contains a data element say data, and the address of the immediate next node say next, with Head holding the address of the first node and the next part of the last node contains head.

Pseudo code:

```//assumed all node has different key, so searching node by key value
while(temp->data!=key)
begin
temp1=temp
temp=temp->next
End while

//node found which is to be interchanged
temp1=temp->next
temp->next=temp1->next
temp1->next=temp
ELSE
temp2=temp->next
temp->next=temp2->next
temp2->next=temp
temp1->next=temp2
End IF-ELSE
End
```

C code:

```#include <stdio.h>
#include <stdlib.h>

typedef struct list
{
int data;
struct list *next;
}node;

void display(node *temp)
{
node *temp1=temp;
printf("\nNow the list is :\n%d->",temp->data);
temp=temp->next;
while(temp!=temp1)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("%d\n",temp1->data);
}

int main(){
int choice,key;

do
{
temp=(node *)malloc(sizeof(node));
if(temp!=NULL)
{
printf("\nEnter the element in the list : ");
scanf("%d",&temp->data);
{
}
else
{
{
temp1=temp1->next;
}
temp1->next=temp;
}
}
else
{
printf("\nMemory not avilable...node allocation is not possible");
}
printf("\nIf you wish to add m ore data on the list enter 1 : ");
scanf("%d",&choice);
}while(choice==1);

printf("\nEnter the data of the node which you want to exchange with it's next : ");
scanf("%d",&key);
while(temp->data!=key)
{
temp1=temp;
temp=temp->next;
}
{
temp1=temp->next;
temp->next=temp1->next;
temp1->next=temp;
}
else
{
temp2=temp->next;
temp->next=temp2->next;
temp2->next=temp;
temp1->next=temp2;
}

return 0;
}
```

Output

```Enter the element in the list : 1

If you wish to add m ore data on the list enter 1 : 1

Enter the element in the list : 2

If you wish to add m ore data on the list enter 1 : 1

Enter the element in the list : 3

If you wish to add m ore data on the list enter 1 : 1

Enter the element in the list : 4

If you wish to add m ore data on the list enter 1 : 1

Enter the element in the list : 5

If you wish to add m ore data on the list enter 1 : 0

Now the list is :
1->2->3->4->5->1

Enter the data of the node which you want to exchange with it's next : 3

Now the list is :
1->2->4->3->5->1
```

Preparation

What's New

Top Interview Coding Problems/Challenges!