Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Write C++ code There are two linked lists A and B containing integers. Write a friend function of LinkedList class to create and return a
Write C++ code
There are two linked lists A and B containing integers. Write a friend function of LinkedList class to create and return a new linked list that contains only those elements that are common in linked lists A and B
LinkedList commonElements(LinkedList A, LinkedList B)
{
}
Use this linked list code
#include
using namespace std;
template
class Node {
public:
T info;
Node *next;
Node(T data) {
next = NULL;
info = data;
}
};
template
class LinkedList {
private:
Node *start;
public:
LinkedList(){
start = NULL;
}
void print(){
Node *curr = start;
while (curr != NULL)
{
cout curr = curr -> next;}cout<}void insertToFront(T data) {Node *newNode = new Node(data);newNode->next = start;start = newNode;}void insertToEnd(T data) {Node *newNode = new Node(data);if(start == NULL){start = newNode;}else {Node *curr = start;while (curr->next != NULL){curr = curr->next;}curr->next = newNode;}}void insertOrdered(T data) {if(start == NULL) {start = new Node(data);}else {Node *newNode = new Node(data);Node *curr = start;Node *prev = NULL;while (curr != NULL && data > curr->info){prev = curr;curr = curr -> next;}if(prev == NULL) {newNode -> next = start;start = newNode;}else if(curr == NULL) {prev->next = newNode;}else {prev->next = newNode;newNode -> next = curr ;}}}bool deleteItem(T data) {if(start == NULL)return false;else {Node *curr = start;Node *prev = NULL;while (curr != NULL && curr->info != data){prev = curr;curr = curr -> next;}if(curr == NULL)return false;else if(prev == NULL) {start = start -> next;delete curr;return true;}else {prev->next = curr -> next;delete curr;return true;}}}};int main() {LinkedList list;list.insertOrdered(5);list.insertOrdered(15);list.insertOrdered(8);list.insertOrdered(25);list.insertOrdered(1);list.insertOrdered(13);list.deleteItem(1);list.deleteItem(8);list.deleteItem(25);list.print();return 0;}
Step by Step Solution
★★★★★
3.47 Rating (157 Votes )
There are 3 Steps involved in it
Step: 1
To create a new linked list containing common elements from two linked lists A and B you can implement a friend function in your LinkedList class Here...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started