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

please help! Sorted link list Help! can you help me write the void SortedInsert(

ID: 3689854 • Letter: P

Question

please help!

Sorted link list Help! can you help me write the void SortedInsert(Node* head, int value) function. thanks.

#include <iostream>
#include <cassert>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;

struct Node {
Node* next = 0;
int data;
~Node(){
if (next != 0){
delete next;
}
}
};

void SortedInsert(Node* head, int value){
//code here
}

int main() {
srand(32);
Node* sortedList = 0;
for (int i = 0; i < 10; i++){
SortedInsert(sortedList, rand() % 100);
}

Node* temp = sortedList;
for (int i=0; i < 9; i++){
assert(temp->data <= temp->next->data);
temp = temp->next;
}

delete sortedList;
}

Explanation / Answer

void SortedInsert(Node* head, int value){
if(head == 0){ //checking empty list
//creaing head node initially
Node temp = new Node;
temp -> data = value;
temp -> next = head;
head = temp;
}
else{
//inserting new node in specific position
while(head->next != 0){
if(head->data > value){
Node temp = new Node;
temp->data = value;
temp->next = head;
head = temp;
break;
}
else{//incrementing head node to point to next node
head = head -> next;
}
}
}
}