0
由於某些原因,我的代碼運行不正常。它會進行編譯,但是當它進入輸出屏幕時,它只會顯示「發生錯誤」。它沒有列出任何種類的錯誤。我一直在嘗試在代碼中查找錯誤,但似乎無法找到它的位置。這裏是我的代碼:C++哈希錶鏈接錯誤
class Node
{
private:
int key;
int value;
Node* next;
public:
Node();
~Node();
void setKey(int num);
int getKey();
void setValue(int x);
int getValue();
void setNext(Node* theNext);
Node* getNext();
};
Node::Node()
{
next = NULL;
}
Node::~Node()
{
}
void Node::setKey(int num)
{
key = num;
}
int Node::getKey()
{
return key;
}
void Node::setValue(int x)
{
value = x;
}
int Node::getValue()
{
return value;
}
void Node::setNext(Node* theNext)
{
next = theNext;
}
Node* Node::getNext()
{
return next;
}
const int SIZE = 7;
class chainTable
{
private:
Node* data[SIZE];
public:
chainTable();
~chainTable();
int chainHash(int num);
void insert(int key, int value);
void printTable();
};
chainTable::chainTable()
{
for (int i = 0; i < SIZE; i++)
{
data[i]->setValue(-1);
}
}
chainTable::~chainTable()
{
}
int chainTable::chainHash(int num)
{
return num % 5;
}
void chainTable::insert(int key, int value)
{
if (data[key]->getValue() == -1)
{
data[key] = new Node;
data[key]->setValue(value);
data[key]->setKey(key);
data[key]->setNext(NULL);
}
else
{
Node* temp = data[key];
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
Node* newEntry = new Node();
newEntry = temp->getNext();
newEntry->setKey(key);
newEntry->setValue(value);
newEntry->setNext(NULL);
}
}
void chainTable::printTable()
{
for (int i = 0; i < SIZE; i++)
{
Node* temp = data[i];
while (temp->getNext())
{
cout << temp->getValue();
}
}
}
int main()
{
chainTable theChain;
int arr[7] = {1,2,5,7,7,9,1};
for (int i = 0; i < 7; i++)
{
int arrHash = theChain.chainHash(arr[i]);
theChain.insert(arrHash,arr[i]);
}
return 0;
}
它的工作!非常感謝!雖然我改變了它,但我仍然有點困惑,爲什麼它在構造函數中不起作用。我沒有創建節點陣列嗎?節點*數據[大小]。這不是一個節點對象嗎? – user3421510
'Node * data []'是一個指向節點對象的指針數組。但是一開始,沒有任何物體會產生錯誤。在插入函數中,使用'new Node',創建一個對象。 – alain
哦,好的。我現在知道了!非常感謝! – user3421510