In: Computer Science
Please use C++ and linked list to solve this problem
Linked list 1 -> 3 -> 4 -> 5-> 6 ->7
replaceNode( 5 , 6) // Replace 5 with 6
result 1 -> 3 -> 4 -> 6 -> 6 ->7
Base code
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int da = 0, Node *p = NULL) {
this->data =
da;
this->next = p;
}
};
class LinkedList {
private:
Node *head, *tail;
int position;
public:
LinkedList() { head = tail = NULL; };
~LinkedList() {
delete head;
delete tail;
};
void print();
void Insert(int da = 0);
}
void LinkedList::Insert(int da) {
if (head == NULL) {
head = tail = new
Node(da);
head->next =
NULL;
tail->next =
NULL;
} else {
Node *p = new
Node(da);
tail->next = p;
tail = p;
tail->next =
NULL;
}
}
int main() {
cout << "Hello World!" <<
endl;
LinkedList l1;
l1.Insert(1);
l1.Insert(3);
l1.Insert(4);
l1.Insert(5);
l1.Insert(6);
l1.Insert(7);
l1.print();
l1.replaceNode( 5 , 6)
l1.print();
cout << "The End!" << endl;
return 0;
}
}
}
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int da = 0, Node *p = NULL) {
this->data = da;
this->next = p;
}
};
class LinkedList {
private:
Node *head, *tail;
int position;
public:
LinkedList() { head = tail = NULL; };
~LinkedList() {
delete head;
delete tail;
};
void print();
void Insert(int da = 0);
void replaceNode(int a, int b);
};
void printList(Node* n)
{
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}
void LinkedList::print() {
printList(head);
}
void LinkedList::Insert(int n)
{
Node *tmp = new Node;
tmp->data = n;
tmp->next = NULL;
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void updateElement(Node* n , int a, int b){
while (n != NULL) {
if(n->data == a) n->data = b;
n = n->next;
}
}
void LinkedList::replaceNode(int a, int b) {
updateElement(head, a, b);
}
int main() {
cout << "Hello World!" << endl;
LinkedList l1;
l1.Insert(1);
l1.Insert(3);
l1.Insert(4);
l1.Insert(5);
l1.Insert(6);
l1.Insert(7);
l1.print();
l1.replaceNode( 5 , 6);
cout<<endl<<endl;
l1.print();
cout<<endl;
cout << "The End!" << endl;
return 0;
}