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

22) The class below defines a insert function shoul should assign data. 12 point

ID: 3726578 • Letter: 2

Question

22) The class below defines a insert function shoul should assign data. 12 points node for a linked list. Write a FUNCTION called INSERT that s a node at the end. Assume that one node named HEAD has already been created. Your ld take any node names as arguments that the user enters in the function call and PLEASE PUT ANSWER HERE class Node string name; int data; Node *next; public: Node() { next = NULL; } void setname(string n) {name = n;} void setdata(int d) (data d;) void setnext(Node *p)f next p;) string getname() (return name;) int getdata() freturn data;) Node getnext) (return *next:)

Explanation / Answer


#include <iostream>

using namespace std;

class Node
{
   string name;
   int data;
   Node * Next;
   public:
   Node()
   {
       Next = NULL;
   }
   void setname(string n)
   {
       name = n;
   }
   void setdata(int id)
   {
       data = id;
   }
   void setnext(Node * p)
   {
       Next = p;
   }
   string getName()
   {
       return name;
   }
   int getdata()
   {
       return data;
   }
   Node getnext()
   {
       return *Next;
   }

   void insertAtEnd(Node* &first, int user_data,string user_name)
   {
       // Creating Node and filling data
       Node* temp = new Node;
       temp->name = user_name;
       temp->data = user_data;
       temp->Next = NULL;

       if(!(first->Next)) { // empty list becomes the new node

           first->Next = temp;
           return;
       } else {
           // find last and link the new node
           Node* last = first->Next;
           while(last->Next)
           {
               // Dummy looop to go at the end
               last=last->Next;
           }
           last->Next = temp;
       }
   }

   void printData(Node * head)
   {
       while(head)
       {
           cout<< (head->name)<<"   "<< head->data << endl;
           head = head->Next;
       }

   }
};


int main()
{
   Node* temp = new Node();
   temp->insertAtEnd(temp,1,"first");
   temp->insertAtEnd(temp,2,"second");
   temp->insertAtEnd(temp,3,"third");
   temp->insertAtEnd(temp,4,"last");
   temp->printData(temp);


   return 0;
}

// Node: AS of now implementation is like from main we are sending data. instead of that we can pass only node address and scan data in function. Please feel free to ask any queries in comment section

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