Answers for "swap two nodes in linked list"

C++
0

swap two nodes in linked list

//not changing the data inside
//Try on your own first
#include<iostream>
using namespace std;
struct node
{
  int data;
  node* next;
};
node * head=NULL;
void insertion(int key)
{
  node *temp=new node;
  temp->data=key;
  temp->next=NULL;
  if(head==NULL)
  {
    head=temp;
  }
  else
  {
    node* ptr=head;
    while(ptr->next!=NULL)
    {
      ptr=ptr->next;
    }
    ptr->next=temp;
  }
}
void swapnode(int x,int y)
{
  if(x==y)
  {
    return;
  }
  node *x_prev=NULL;
  node* x_curr=head;
  node* y_prev=NULL;
  node* y_curr=head;
  while(x_curr!=NULL&&x_curr->data!=x)
  {
    x_prev=x_curr;
    x_curr=x_curr->next;
  }
  while(y_curr!=NULL&&y_curr->data!=y)
  {
    y_prev=y_curr;
    y_curr=y_curr->next;
  }
  if(x_curr==NULL||y_curr==NULL)
  {
    return;
  }
  if(x_prev!=NULL)
  {
    x_prev->next=y_curr;
  }
  else
  {
    head=y_curr;
  }
  if(y_prev!=NULL)
  {
    y_prev->next=x_curr;
  }
  else
  {
    head=x_curr;
  }
  node *temp=y_curr->next;
  y_curr->next=x_curr->next;
  x_curr->next=temp;
}
void print()
{
  node* temp=head;
  while(temp!=NULL)
  {
    cout<<temp->data<<" ";
    temp=temp->next;
  }
}
int main()
{
  int n;
  cin>>n;
  int value;
  for(int i=0;i<n;i++)
  {
    cin>>value;
    insertion(value);
  }
  int p,q;
  cin>>p>>q;
  swapnode(p,q);
  print();
  return 0;
}
Posted by: Guest on July-25-2021

Code answers related to "swap two nodes in linked list"

Browse Popular Code Answers by Language