2012-12-05 80 views
0

我想實現一個接收List和Int作爲參數的bool函數,並且應該插入int並返回true,如果int不存在於列表中,或者false if它已經存在了,我已經使用這個函數工作了幾個小時,並且if-else語句可以插入sorted int,問題(和崩潰)是如何檢查該值是否已經存在並返回false,這裏是我的函數: 聲明結構布爾分類插入函數檢查如果int已經存在列表中

typedef struct E_Type * List; 
struct E_Type 
{ 
    int data; 
    List next = 0; 
}; 

和功能

bool insert(List & l, int data) 
{ 

    List current = l; 
     do{//check if the int is already in the list 
      current->data; 
      current = current->next; 
     //return false; 
    }while (current->data == data); 

     if (l == 0 || l->data > data){ 
       List new_list = new E_Type; 
       new_list->data = data; 
       new_list->next = l; 
       l = new_list; 
      return true; 
     } 

     else if(l->data < data){ 
      insert(l->next, data); 
      return true; 
    } 



    } 
+0

除非你需要自己編寫所有代碼,否則請考慮使用一個'std :: set',它已經幾乎完全實現了你想要實現的東西。 –

+0

是的,我知道關於集合,但這是一種課程作業/任務/實驗室 – EmilDo

+1

好吧 - 看了一下代碼,我沒有看到任何看起來像檢查'next'指針是否不是-null,這通常是遍歷鏈表所必需的。 –

回答

1
do{ 
     //this line doesn't really do anything... 
     current->data; 
     //moving current forward, good. 
     current = current->next; 
//If current->data is less than data in the list, it will exit the loop here anyway. 
}while (current->data == data); 

您還沒有檢查您是否已到達列表的末尾。也許你正在試圖做的是這樣的:

//This is correct for for iterative approach, but I don't think this is really what you need, either... 
while(current != null) { 
    if (current->data == data) 
     return false; 
    current = current->next; 
} 

然而,你可能不希望使用迭代這樣做此檢查在遞歸函數,所以反而,只需更換與整個位:

if (current->data == data) 
    return false; 

,並返回通過遞歸調用正確的值,你會想改變:

else if(l->data < data){ 
    insert(l->next, data);   //Recursive call 
    return true; //you don't want to just return true, return what the recursive call returns! 
} 

要:

else if(l->data < data){ 
    return insert(l->next, data); 
} 
+0

非常感謝,解決方案是while-if方法,我以前也嘗試過,但可能錯誤地放置了導致程序崩潰的返回false語句。再次感謝 – EmilDo

+0

沒問題。您還應該看到Jerry Coffin對於檢測列表結束的終止條件的評論。我沒有在這個答案中解決這個問題,但是你確實需要這樣做,因爲要插入的數據大於列表中的最後一個值。 – femtoRgon

相關問題