2013-10-16 71 views
1

我正在为有序链接列表写入插入算法。我已经完成了大部分算法,但是while循环条件将我抛弃了。我认为其余部分我有正确的,但任何帮助,将不胜感激,谢谢!为有序链接列表写入插入算法C++

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 
} 
+0

神秘代码大概是比较你的两个'ListNode'结构所需要的。如果不知道'ListNode'是什么或者应该如何比较,那么没有人可以帮助你。 –

+0

MyLinkedList类包含private:ListNode *头。 ListNode结构包含:int Key,double dataValue和ListNode * next。 newNode中的下一个指针已经被设置为NULL。 –

回答

3

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

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

在假设该列表是基于键值进行排序,while循环条件应该是这样的:

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

的代码的其余部分似乎与之一致。

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

+0

谢谢你的帮助! –

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

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