1

我正在为有序链表编写插入算法。我已经完成了大部分算法,但是一个 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
}
4

2 回答 2

3

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

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

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

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

其余的代码似乎同意它。

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

于 2013-10-16T20:28:42.260 回答
0
while((**???**) && (**???**))

您需要在此处插入比较。无论 内部是什么类型的数据ListNode,您都应该有某种方法来比较其中的两个。如果它不是原始类型,我怀疑你有一个重载的运算符。

于 2013-10-16T20:15:20.950 回答