为有序链表编写插入算法C++

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

本文关键字:插入 算法 C++ 链表      更新时间:2023-10-16

我正在为有序链表编写插入算法。我已经完成了大部分算法,但是一个while循环条件让我失望了。我认为其余部分我是正确的,但任何帮助将不胜感激,谢谢!

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
}

我假设您具有以下ListNode结构(基于您之前的评论)。

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

假设列表是根据键值排序的,while 循环条件应如下所示:

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

代码的其余部分似乎同意它。

如果排序列表的比较方法与简单的键比较不同,则第二个参数需要更改。

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

您需要在此处插入比较。无论ListNode里面有什么样的数据,你都应该有办法比较其中的两个。我怀疑你有一个重载的运算符,如果它不是基元类型。