Write C++ code There are two linked lists A and B containing integers. Write a friend function
Fantastic news! We've Found the answer you've been seeking!
Question:
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;}
Related Book For
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch
Posted Date: