Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given a head node of singly linked list, write a function to double the value in

ID: 3850889 • Letter: G

Question

Given a head node of singly linked list, write a function to double the value in each node. A new node should be inserted after each node with the value equal to double its previous. The function should return the head node after inserting the necessary nodes. (bold is what is given)

struct Node{

int value;

Node *next;

}

Node *DoublePrevious(Node *head)

Examples:

Given linked list : 1 -> 2 -> 3 -> nullptr

Output : 1 -> 2 -> 2 -> 4 -> 3 -> 6 -> nullptr

Given linked list : 5 -> 7 -> 9 -> nullptr

Output : 5 -> 10 -> 7 -> 14 -> 9 -> 18 -> nullptr

Explanation / Answer

PROGRAM CODE:

#include <iostream>

using namespace std;

struct Node{
int value;
Node *next;
};

Node* DoublePrevious(Node *head)
{
   Node *temp = head;
   //new head that holds the old value and the doubled values
   Node *newHead = new Node;
   //pointer to the new head
   Node *temp1 = newHead;
   while(temp != NULL)
   {
       // getting the current element value
       temp1->value = temp->value;
       temp1->next = new Node;
       //doubling the current value and making a new node
       temp1->next->value = temp->value*2;
       temp1 = temp1->next;
       if(temp->next == NULL)
           temp1->next = NULL;
       else temp1->next = new Node;
       temp1 = temp1->next;
       temp = temp->next;
   }

   return newHead;
}
//function to display the nodes on screen
void display(Node *head)
{
   Node *temp = head;
   while(temp != NULL)
   {
       cout<<temp->value<<"->";
       temp = temp->next;
   }
   cout<<"nullptr"<<endl;
}

//driver function to test the code
int main() {
   Node node1, node2, node3, *head;
   node1.value = 5;
   node1.next = &node2;
   node2.value = 7;
   node2.next = &node3;
   node3.value = 9;
   node3.next = NULL;
   head = &node1;
   //displaying before calling the function
   display(head);
   head = DoublePrevious(head);
   //after calling the function
   display(head);
   return 0;
}

OUTPUT:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote