我需要創建一個類成員(二進制)的鏈表,並且我遇到了無限循環問題。二進制類只包含度(int)和下一個節點指針。 在二進制類中,二進制鏈接列表的實現在set_bit方法內執行。 set_bit方法需要兩個整數,它們是1/0 int(位)和int度。這一點雖然不是必需的。使用while循環創建鏈接列表
的SET_BIT方法是如下:
void Binary::set_bit(int b, int d){
BinaryNode* current = firstTerm;
BinaryNode* toSet;
if (current == NULL) {
firstTerm = new BinaryNode(d, NULL);
current = firstTerm;
cout << "\nd: " << d << " <--> current degree: " << current->degree << endl;
system("pause");
} else {
while (current != NULL){
firstTerm = new BinaryNode(d, current);
cout << "\nd: " << d << " <--> current degree: " << current->degree << endl;
cout << "first term: " << firstTerm->degree << endl;
system("pause");
}
}
}
上的main.cpp文件
,我試圖設置以下位:
b1.set_bit(1, 2);
b1.set_bit(1, 5);
b1.set_bit(1, 0);
b1.set_bit(0, 2);
該方法是設定第一比特(2) ,並進入下一個(5),然後開始嘗試設置該位的無限循環。 我在哪裏錯了? 我已經問了我的實驗室老師的幫助,他向我提供了以下代碼: 爲什麼實驗室教師不工作的代碼?
void Binary ::set_bit(int b , int d){
BinaryNode * current = firstTerm;
if (current == NULL){
firstTerm = new BinaryNode(d,NULL); // Corrected Line
}
while (current != NULL){
firstTerm = new BinaryNode(d,firstTerm); // Corrected Line
}
}
感謝
您不會在while循環中更改當前條件(current!= NULL)將始終爲真。 – drescherjm 2014-09-29 19:55:10