1

I'm writing an insert algorithm for an ordered linked list. I've got most of the algorithm completed, but the one while loop condition is throwing me off. I think the rest of it I have correct, but any help with it would be appreciated, thanks!

bool MyLinkedList::Insert(ListNode *newNode)
{
    // Assume ListNode is a structure and contains the variable int key;
    // Assume the function returns true if it successfully inserts the node
    ListNode *back = NULL, *temp = head;
    if(head == NULL)   // Check for inserting first node into an empty list
    {
        head = newNode;
        return true;
    }   
    else
    {       // Search for insert location
        while((**???**) && (**???**))
        {
            back = temp; // Advance to next node
            temp = temp -> next; 
        {

        // Check for inserting at head of the list
        if(back == NULL) 
        {
            newNode -> next = head; // Insert at head of list
            head = newNode;
            return true;
        }
        else // Insert elsewhere in the list
        {
            newNode -> next = temp;
            back -> next = newNode;
            return true;
        }
    }
    return false;  // Should never get here
}
2
  • The mystery code is presumably whatever is needed to compare two of your ListNode structures. Without know what a ListNode is or how they should be compared no one can help you with that. Commented Oct 16, 2013 at 20:12
  • MyLinkedList class contains private: ListNode *head. the ListNode structure contains: int Key, double dataValue, and ListNode *next. the next pointer in newNode has already been set to NULL. Commented Oct 16, 2013 at 20:14

2 Answers 2

3

I am assuming you have the following structure for ListNode (based on your prior comment).

struct ListNode {
      int Key;
      double dataValue;
      ListNode *next;
}

On the assumption that the list is ordered based on the key values, the while loop condition should look like this:

 while((temp != NULL) && (temp->Key < newNode->Key))

The rest of the code seems to agree with it.

The second argument would need change if the comparison methodology for ordering the sorted list is different than simple key comparison.

Sign up to request clarification or add additional context in comments.

Comments

0
while((**???**) && (**???**))

You need to insert your comparisons here. Whatever kind of data is inside the ListNode, you should have some way of comparing two of them. I suspect you have an overloaded operator if it isn't a primitive type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.