Answer to Question #233665 in C++ for David

Question #233665
The function below should insert a value as the head of a given UNORDERED linked list. Be
careful to first search for the given value. The value is inserted only if it does not exist in the
list. If the value exists, the function does nothing. Use Linked list implementation of Task 1 to
make this function run. Write down the code of insert function run the code, take snap shot
and paste it in your document.
struct Node{
int data;
Node* next;
};
The function prototype is given. Implement the function.
void insert(Node* &head, int value);
1
Expert's answer
2021-09-06T05:29:07-0400
#include<bits/stdc++.h>
using namespace std;


 class Node
 {
     public:
      
       int data;
        Node* nextNode;
 };
 bool searchElement(Node*node, int data)
 {
     Node* curr=node;
     
      while(curr!=NULL)
      {
          if(curr->data==data)
          {
              return true;
          }
          
          curr=curr->nextNode;
      }
      
      return false;
 }
 void display(Node *head){
 	while(head !=NULL){
 		cout<<head->data<<"=>  \t";
 		head = head->nextNode;
	 }
 }
 void insert(Node** head, int data)
 {
     Node* temp= new Node();
     
     temp->data=data;
     
     temp->nextNode=*head;
     
     *head=temp;
 }
 
 
 int main()
 {
     Node* head=NULL;
     
     int data;
     
      cout<<"Enter data :"<<endl;
       cin>>data;
       
        insert(&head,21);
        insert(&head,32);
        insert(&head,45);
        insert(&head,56);
        if(searchElement(head,data)==1){
        	cout<<"The element already exist\n";
		}
		else{
			cout<<"Element inserted successfully\n";
			insert(&head,data);
		}
					cout<<"The list is: \n";


        display(head);
 }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS