Sorted link list Help! can you help me write the void SortedInsert(Node* head, i
ID: 3689837 • Letter: S
Question
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
Answer:
The implementation of void SortedInsert(Node* head, int value) function is as shown below :
void SortedInsert(Node* head, int value)
{
Node* new_node =(Node*)malloc(sizeof(Node));
Node* current;
new_node->data = value;
new_node->next = NULL;
if (head == NULL || (head)->data >= new_node->data)
{
new_node->next = head;
head = new_node;
}
else
{
current = head;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.