简体   繁体   中英

Writing an Insert Algorithm for an Ordered Linked List C++

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
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM