Rebecca2003
asked on
insertion into linked list
I wanted to insert a value to a linked list in ascending order. But when i insert 5,10,2 - it will print out 5,2,10. When i try 4,3,8 - its correct! Pls correct my mistakes below.
void insert(nodePtr &head, value val)
{
nodePtr newNode = new node;
newNode->num = val;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else if(head->next == NULL)
{
if(head->num > val)
{
newNode->next = head;
head = newNode;
}
}
else
{
nodePtr search = head;
nodePtr temp;
while(search != NULL)
{
if(search->next == NULL)
{
search->next = newNode;
break;
}
if(search->next->num > val)
{
temp = search->next;
search->next = newNode;
newNode->next = temp;
break;
}
search = search->next;
}
}
}
void insert(nodePtr &head, value val)
{
nodePtr newNode = new node;
newNode->num = val;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else if(head->next == NULL)
{
if(head->num > val)
{
newNode->next = head;
head = newNode;
}
}
else
{
nodePtr search = head;
nodePtr temp;
while(search != NULL)
{
if(search->next == NULL)
{
search->next = newNode;
break;
}
if(search->next->num > val)
{
temp = search->next;
search->next = newNode;
newNode->next = temp;
break;
}
search = search->next;
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Rebecca2003:
You should probably keep one question in one posting rather than here and in https://www.experts-exchange.com/questions/20796480/c-insertion-for-linked-list.html
You should go to Community Support and have one of them removed.
-bcl
You should probably keep one question in one posting rather than here and in https://www.experts-exchange.com/questions/20796480/c-insertion-for-linked-list.html
You should go to Community Support and have one of them removed.
-bcl
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:
Accept: sbooth17 {http:#9740825}
Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
Tinchos
EE Cleanup Volunteer
I will leave the following recommendation for this question in the Cleanup topic area:
Accept: sbooth17 {http:#9740825}
Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
Tinchos
EE Cleanup Volunteer
Use type int if i am right.
Regards, Alex