In div c please with comments and check output thanks Q2 Sw
In div c++ // please with comments and check output thanks
Q2. Swap two adjacent elements by adjusting only the links (and not the data) using singly linked list.
-----------------------------------------------------
Solution
#define NULL 0
#include <iostream>
/*
Name:
ID:
Section:
*/
using namespace std;
struct Node
{
int item; //data
Node *next; //pointer to the next node in the list
};
Node* createNode(int);
void appendNode(Node*&, int);
void displayList(Node*);
void printLists(Node*, Node*);
void swapNodes(Node* &head,int s,int t);
int main()
{
Node* L = NULL, *P = NULL;
appendNode(L, 1);
appendNode(L, 2);
appendNode(L, 3);
appendNode(L, 4);
appendNode(L, 6);
appendNode(L, 8);
displayList(L);
appendNode(P, 1);
appendNode(P, 2);
appendNode(P, 4);
appendNode(P, 6);
displayList(P);
swapNodes(L,2,3); //It should swap the links of nodes 2 and 3 in L.
displayList(L); //display after swapping
return 0;
}
//swap the node containing item s with the next node containing item t in the list
void swapNodes(Node* &head, int s,int t)
{
//write your code here
if(s==t) //if both given item is equal return
return;
struct Node* currs=head;
struct Node* prevs=NULL;
struct Node* currt=head;
struct Node* prevt=NULL;
//searching position of item s
while(currs && currs->item != s)
{
prevs=currs;
currs=currs->next;
}
//searching position of item t
while(currt && currt->item != t)
{
prevt=currt;
currt=currt->next;
}
if(currs == NULL || currt==NULL)
return;
//swapping if item s is not head
if(currs->item != head->item){
prevs->next=currt;
currs->next=currt->next;
currt->next=currs;}
else{ //swapping if item s is head
currs->next=currt->next;
currt->next=currs;
head=currt;
}
}
Node* createNode(int value)
{
Node *node = new Node;
node->item = value;
node->next = NULL;
return node;
}
void appendNode(Node* &head, int value)
{
Node *newNode, *currNode;
newNode = createNode(value);
if(head == NULL) //the list is empty
head = newNode; //make a new list
else
{ //list is not empty
currNode = head; //current node points to the list head
while (currNode->next != NULL) //move current node in the list
currNode = currNode->next;
currNode->next = newNode; //add new node at the end
}
}
void displayList(Node* head)
{
cout<< \"List:\";
Node* currNode = head;
while (currNode != NULL)
{
cout<<currNode->item<<\", \";
currNode = currNode->next;
}
cout<<endl;
}
/*****OUTPUT**********
List:1, 2, 3, 4, 6, 8,
List:1, 2, 4, 6,
List:1, 3, 2, 4, 6, 8,
******OUTPUT*********/
//Note this code has been tested on g++ compiler,please do ask in case of any doubt,Thanks.


