In: Computer Science
Add the operation Insert to the linkedListClass. An Insert operation inserts a new item after a given key in the linked list. The method headline can be void Insert(int item, int key), where the first parameter is the new item, and the second parameter is the key of the item before the new item.
void Insert(int item, int key) { Node *start = head; // Assuming class has instance member head which points to first node. if(start == NULL) { // list has no nodes till now. Create a new node with item // as this is the first node in list, its next should be null. head = new Node(); head->data = item; head->next = NULL; return; } // The list is not empty at this point, Hence, We need to find a node which has the key data // or else if the key node does not exist in the list, we should reach to last node // and insert the new node after that // add new node after the given key while(start->next != NULL && start->data != key) { start = start->next; } // making the new node next node as the start node where key data exists Node *tmp = new Node(); tmp->data = item; tmp->next = start->next; start->next = tmp; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.