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

//Precondition: A pointer to a LinkedList object created on the heap that //cont

ID: 3868970 • Letter: #

Question

//Precondition: A pointer to a LinkedList object created on the heap that //contains all nodes in sorted (ascending) order. The list may be empty. //The list may have multiple copies of the same element //Postcondition: Insert a node with the given value at the appropriate //location in the list, so that the new list also contains nodes in sorted //(ascending) order. The list may have multiple copies of the same element void insertNodeTosortedList(LinkedList *list, int value): assert (list! = NULL);//if list is NULL, we can do nothing.

Explanation / Answer

//This method is for inserting a value into a sorted list.
struct node * insertNodeToSortedList(struct node * head, int value)
{

int position = 0;
struct node * temp = head;
while(temp != NULL)
{
if(temp->data > value)
break;

temp = temp->next;
position++;
}
head = addAtPosition(head, value, position);
return head;
}

//This method inserts that value at particular position mentioned in above method.
struct node * addAtPosition(struct node *head, int value, int position)
{
int initial_position = 0;
struct node * mover = head;

while(initial_position!= pos)
{
mover = mover -> next;
initial_position++;
}

struct node * temp = (struct node*)malloc(sizeof(struct node));
temp -> data = value;

temp -> next = mover -> next;
mover -> next = temp;

return head;
}