Solved programming problem

Swap Two Value By Index in Single Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

int Print(node *head)

{

    node *temp=head;

    if(head==NULL)

    {

        cout<<"
This Linked List is Empty
";

        return 0;

    }

    else

    {

        cout<<"Liked List: "<<endl;

        while(temp !=NULL)

        {

            cout<<temp->data<<" ";

            temp=temp->next;

        }

    }

}

void swap_node(node *head,int n,int m)

{

    node *n_node,*m_node;

    int i;

    n_node=head;

    m_node=head;

    for(i=1; i<n; i++)

    {

        n_node=n_node->next; ///find the nth position

    }

    for(i=1; i<m; i++)

    {

        m_node=m_node->next; ///find the mth position

    }

    int temp;

   

    ///swap n and m position

    temp = n_node->data;

    n_node->data=m_node->data;

    m_node->data=temp;

}

int main()

{

    int n,m,flag;

    node *head=NULL;

    node *last,*temp,*start=head;

    do

    {

        cout<<"Press 1 to Insert Data: ";

        cin>>flag;

        if(flag!=1)break;

        temp=new node();

        cout<<"Data: ";

        cin>>temp->data;

        temp->next=NULL;

        if(start==NULL)

        {

            start=temp;

            head=temp;

        }

        else

        {

            last = start;

            while(last->next!=NULL)

            {

                last = last->next;

            }

            last->next=temp;

        }

    }

    while(flag==1);

    Print(head);

    cout<<"
Enter Two Position for Swap: ";

    cin>>n;

    cin>>m;

    swap_node(head,n,m);

    cout<<"
After Swap: ";

    Print(head);

    return 0;

}

Output

Press 1 to Insert Data: 1
Data: 1
Press 1 to Insert Data: 1
Data: 2
Press 1 to Insert Data: 1
Data: 3
Press 1 to Insert Data: 1
Data: 4
Press 1 to Insert Data: 1
Data: 5
Press 1 to Insert Data: 0
Liked List:
1 2 3 4 5

Join the discussion

Add your comment