2011-02-15 79 views
1

我有一個指針的問題,並圍繞它不能得到..指針比較問題

在哈希表中實現,我已下令節點的每個bucket.The問題名單上有它在插入函數,以比較下一個節點是否大於當前節點(如果是,則插入該位置)並保持順序。

你可能會發現這個哈希實現很奇怪,但我需要能夠做大量的查找(但有時也很少),並計算重複次數,如果它已經插入(所以我需要快速查找,因此哈希,我認爲自平衡樹是AVL或RB樹,但我不知道它們,所以我採用了我知道如何實現的解決方案......它們對於這類問題更快嗎?),但是我當我完成時還需要通過訂單來檢索它們。 之前我有一個簡單的列表,我會檢索數組,然後做一個QuickSort,但我想我可以通過保持列表的順序來改善事情。

我有什麼映射這是一個27位無符號整數(最準確3​​個9位數字,但我把它們轉換成27位數字做的(Sr < < 18 | SG < < 9 |銻),使得在同一如果你知道一個很好的函數將27位int映射到12-13-14位表讓我知道,我現在只是做典型的mod素數解決方案

這是我的hash_node結構:

class hash_node { 
public: 
    unsigned int hash_value;  
    int repetitions; 
    hash_node *next;      

    hash_node( unsigned int hash_val, 
        hash_node *nxt); 
~hash_node(); 
}; 

而這就是問題的來源

void hash_table::insert(unsigned int hash_value) { 

unsigned int p = hash_value % tableSize; 
if (table[p]!=0) { //The bucket has some elements already 
hash_node *pred; //node to keep the last valid position on the list 
    for (hash_node *aux=table[p]; aux!=0; aux=aux->next) { 
      pred = aux; //last valid position 
     if (aux->hash_value == hash_value) { 
       //It's already inserted, so we increment it repetition counter 
       aux->repetitions++; 
      } else if (hash_value < (aux->next->hash_value)) { //The problem 
        //If the next one is greater than the one to insert, we 
        //create a node in the middle of both. 
     aux->next = new hash_node(hash_value,aux->next); 
     colisions++; 
        numElem++; 
       } 
    }//We have arrive to the end od the list without luck, so we insert it after 
    //the last valid position 
ant->next = new hash_node(hash_value,0); 
colisions++; 
    numElem++; 
}else { //bucket it's empty, insert it right away. 
    table[p] = new hash_node(hash_value, 0); 
    numElem++; 
} 

}

這是GDB顯示:

Program received signal SIGSEGV, Segmentation fault. 
0x08050b4b in hash_table::insert (this=0x806a310, hash_value=3163181) at ht.cc:132 
132     } else if (hash_value < (aux->next->hash_value)) { 

有效地指示我比較記憶ADRESS具有價值,對不對? 希望很明顯。再次感謝!

+0

你可以驗證`aux-> next`不是NULL嗎? – chrisaycock 2011-02-15 18:03:06

+0

嗯,我是這個學科的講座之一,也是這個學生參加的編程比賽的組織者。隨時可以幫助他,但假設學生必須自己解決比賽,或者只是閱讀不同的節目源,而不是使用積極的查詢來社區。 無論如何,正如我檢測到這個查詢,任何其他參與者可以,並且副本是完全禁止的........ – 2011-03-06 10:15:06

回答

2
aux->next->hash_value 

沒有檢查「next」是否爲NULL。

+0

是的,你們都是完全正確的... ...那很快(和愚蠢!)現在我也知道這個實現在一些數據集中更快,但是大多數速度更慢。謝謝! – asendra 2011-02-15 18:06:27

1

aux-> next可能在那一點是NULL?我看不到你在哪裏檢查aux-> next是否爲NULL。