LL14

#include <bits/stdc++.h>
using namespace std;

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

void swapNodes(node **head_ref, int x, int y)
{
if (x == y) return;

node *prevX = NULL, *currX = *head_ref;
while (currX && currX->data != x)
{
prevX = currX;
currX = currX->next;
}

node *prevY = NULL, *currY = *head_ref;
while (currY && currY->data != y)
{
prevY = currY;
currY = currY->next;
}

if (currX == NULL || currY == NULL)
return;

if (prevX != NULL)
prevX->next = currY;
else
*head_ref = currY;

if (prevY != NULL)
prevY->next = currX;
else
*head_ref = currX;

node *temp = currY->next;
currY->next = currX->next;
currX->next = temp;
}

void push(node** head_ref, int new_data)
{
node* new_node =new node();

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;
}

void printList(node *Node)
{
while(Node != NULL)
{
cout<<"-->"<<Node->data;
Node = Node->next;
}
}

int main()
{
node *start = NULL;

int n,x,y;
  cin>>n;
  for(int i=0;i<n;i++)
    {
      int a;
      cin>>a;
      push(&start,a);
    }
cin>>x>>y;
  cout << "Linked list before Swapping : ";
  printList(start);
  cout<<endl;
 
swapNodes(&start, x, y);

cout << "Linked list after Swapping : ";
  printList(start);

return 0;

No comments:

Post a Comment

SRM ELAB SOLUTUONS   DATA-STRUCTURE                                                                             **IF THE PROGRAM DON...