2013-10-16 33 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裏面有什麼樣的數據,你都應該有一些比較其中兩種的方法。如果它不是原始類型,我懷疑你有一個重載操作符。