Link to home
Start Free TrialLog in
Avatar of Rebecca2003
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;
            }

      }
}
ASKER CERTIFIED SOLUTION
Avatar of sbooth17
sbooth17

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What type is val and num? If that are strings then "10" is less "2" because comparision works lexicographically.
Use type int if i am right.

Regards, Alex
Avatar of bcladd
bcladd

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
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