These are C++ ( Computer Science II ) programming problem. Please provide the de
ID: 3582418 • Letter: T
Question
These are C++ ( Computer Science II ) programming problem. Please provide the detailed answer the following problems.
We want to implement a linked list that is used to store integers in increasing order. The nodes of the linked list have two public variables: int m value and Node *m next. The pointer variable m head points to the first node in the list a. Write a piece of code that inserts a new node with value val into the list b. Write a piece of code that removes all nodes with a given value ValExplanation / Answer
#include<iostream>
using namespace std;
struct node
{
int m_value;
struct node *m_next;
};
typedef struct node Node;
class linked_list
{
Node *head;
void printReverse(Node *root)
{
if (root == NULL)
return;
printReverse(root->m_next);
cout << "m_value = " << root->m_value << endl;
}
public:
linked_list()
{
head = NULL;
}
void insert_node(int val)
{
Node *tmp, *cur = head,*newNode;
int change = 0;
newNode = new Node;
newNode->m_value = val;
newNode->m_next = NULL;
//if first node assign head pointer with first node
if (head == NULL)
{
head = newNode;
}
else
{
Node *prev = cur;
while (cur != NULL)
{
//if cur value greater then swap new node with current
if (cur->m_value > val)
{
if (head == cur)
{
head = newNode;
tmp = cur;
newNode->m_next = tmp;
prev = head;
change = 1;
break;
}
else
{
newNode->m_next = cur;
prev->m_next = newNode;
change = 1;
break;
}
}
prev = cur;
cur = cur->m_next;
}
if (!change)
prev->m_next = newNode;
}
}
void delete_node(int val)
{
Node *tmp, *cur = head, *prev = cur,*next;
while (cur != NULL)
{
prev = cur;
if (cur->m_value == val)
{
if (head == cur)
{
head = head->m_next;
}
else
{
next = cur->m_next;
prev->m_next = next;
delete cur;
}
}
cur = cur->m_next;
}
}
void print_reverse(linked_list &list)
{
if (list.head != NULL)
{
printReverse(head);
}
return;
}
};
int main()
{
linked_list list1;
//insert values into list
list1.insert_node(5);
list1.insert_node(2);
list1.insert_node(3);
list1.insert_node(1);
list1.insert_node(6);
list1.insert_node(0);
list1.insert_node(4);
cout << "Reversed linked list: " << endl;
list1.print_reverse(list1);
}
----------------------------------------------------------------------------------------------------------------------------------------------------------
Reversed linked list:
m_value = 6
m_value = 5
m_value = 4
m_value = 3
m_value = 2
m_value = 1
m_value = 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.