2014-09-29 37 views
-1

我需要創建一個類成員(二進制)的鏈表,並且我遇到了無限循環問題。二進制類只包含度(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 
    } 
} 

感謝

+0

您不會在while循環中更改當前條件(current!= NULL)將始終爲真。 – drescherjm 2014-09-29 19:55:10

回答

0

當然,你最終會得到無限循環,因爲當u請嘗試將第二個節點,current != NULL始終是真實的,這意味着else部分被調用。不幸的是,裏面有一個while loop,其條件總是如此。

+0

因此,即使我創建新節點 - >下一個== NULL,這並不能解決問題。 – JRW2252 2014-09-29 19:48:18

+0

我使用該設置的唯一原因是由於我的實驗指導員爲我提供的代碼示例。我只是試圖實現它的功能。 – JRW2252 2014-09-29 19:56:11