Answer to Question #265797 in C++ for Ahmed Ali

Question #265797

Q: Suppose there is link list as follows:


Element : Address

5 : 1000

10 : 1500

15 : 2000

20 : 3000


You need to write a pseudo code to insert new node after (15) and set its value as

18. You can suppose the values of address.


1
Expert's answer
2021-11-14T09:22:09-0500
#include <iostream>
using namespace std;
 


struct LinkedList
{
   int item;
   int address;
   struct LinkedList *nextNode;
};


void push(struct LinkedList** list, int data, int add)
{
   
   struct LinkedList* new_node = new LinkedList;
 
   
   new_node->item = data;
 
   new_node->address = add;
   new_node->nextNode = (*list);
 
   (*list) = new_node;
}
 


void insertAfter(struct LinkedList* node, int data, int add)
{
  
if (node == NULL)
{
   cout<<"The previous is null"; return;
   
   
    } 
 
   struct LinkedList* new_node =new LinkedList; 
 
   new_node->item = data;
   new_node->address = add;
 
   new_node->nextNode = node->nextNode;
 
    
    node->nextNode = new_node;
}
 


void append(struct LinkedList** node, int data, int add)
{


struct LinkedList* new_node = new LinkedList;
 
struct LinkedList *last_node = *node;
 


new_node->item = data;
new_node->address = add;


new_node->nextNode = NULL;
 


if (*node == NULL)
{
*node = new_node;
return;
}


while (last_node->nextNode != NULL)
last_node = last_node->nextNode;
 
last_node->nextNode = new_node;
return;
}
 


void displayList(struct LinkedList *node)
{


   while (node != NULL)
   {
      cout<<node->item<<", "<<node->address<<endl;
      node = node->nextNode;
   }
 
if(node== NULL)
cout<<"null"; 
} 


int main() 
{ 


struct LinkedList* head = NULL; 
 


append(&head, 5,1000); 
 
push(&head, 15,2000);
push(&head, 10,1500); 
 
 
 
append(&head, 20,3000);
 
 
insertAfter(head->nextNode, 18,4000);
 
cout<<"Linked list: "<<endl;
displayList(head);
 
return 0;
}

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