I'm having trouble figuring out how to insert an element into a sorted list. I am new to linked lists and I'm still having trouble.The following function takes an predefined list and an element as arguments. I have white boarded the whole thing but I still can't figure it out. Thank you for your help.
/*
* function: lst_insert_sorted
*
* description: assumes given list is already in sorted order
* and inserts x into the appropriate position
* retaining sorted-ness.
* Note 1: duplicates are allowed.
*
* Note 2: if given list not sorted, behavior is undefined/implementation
* dependent. We blame the caller.
* So... you don't need to check ahead of time if it is sorted.
*/
void lst_insert_sorted(LIST *l, ElemType x) {
NODE *p = l->front;
NODE *temp;
NODE *current = p;
NODE *prev;
NODE *next;
if (p->val >= x) { // Base Case if
p->val = x;
}
while (p !=NULL) {
prev = current;
temp = prev->next;
next = current->next;
if (next->val >= x) {
temp->val = x;
}
}
return 0;
}