Reputation: 151
This is a function defined in c++ style to insert an value in a presorted linked list. Function arguments are pointer to head of linked list and inserting value. Please ignore the end condition and list is sorted in non increasing order:
list 15->12->9->6->3
inserting element 7
required o/p : 15->12->9->7->6->3
but it's giving 9->7->6->3
please point out my error as i tried but didn't get it since i passed the double pointer to first node but didn't change in function.
void llist::Insert_in_sorted_list(node **head_ref, int data) {
node *head, *ptr;
head = *head_ref;
while (head->next->data > data) {
head = head->next;
}
ptr = new node;
ptr->data = data;
ptr->next = head->next;
head->next = ptr;
}
Upvotes: 0
Views: 67
Reputation: 1222
Most probably you are using the name 'head
' itself in the main program as the starting point of the list. And in this function you are essentially using "head" and making "head" traverse till the next element smaller than the input value is encountered.
So the head is now the element just before the entered value.
To resolve this issue just rename the node pointer '*head
' to something like say '*currentNode
' in this Insert_in_sorted_list(node **head_ref,int data)
function.
Upvotes: 0