簡體   English   中英

追加節點雙鏈表

[英]Appending Node Doubly Linked List

我正在嘗試將節點的追加到新列表。 該程序在while循環中崩潰。

void DLL:append(string ss, string name, int & count){
  Node *temp;
  Node *newNode = new Node();
  newNode->ssn = ss;
  newNode->name = name;
  newNode->next = NULL;
  newNode->prev = NULL;
  temp = headPtr;

  if(headPtr == NULL){
   headPtr = newNode;
   count++;
  }else{
   while(temp->next != NULL){
    temp = temp->next;
   }
   newNode->prev = temp;
   newNode->next = NULL;
   temp->next = newNode;
   count++;
  }
 }
}

我也嘗試過使用它代替while循環,但是結果相同:

while(temp != NULL){
 ...
 temp = temp->next
}

任何幫助將不勝感激!

編輯:將上面的第二種情況更改為

while(temp->next != NULL){
 ...
 temp = temp->next;
}

它遍歷了整個過程,然后顯示了其他語言的字符以及符號等,然后依次顯示了我表面上的每個文件夾,直到它最終崩潰:c

您當前循環直到temp為NULL。 當達到此目標時,可以通過執行temp->next取消引用它。 那是UB,這是程序崩潰的原因。

如下更改while循環,以便在您到達最后一個元素(即,下一個元素為NULL)時停止:

while(temp->next != NULL){
    temp = temp->next
}

請注意,由於有if子句,因此在循環開始時temp沒有為NULL的風險。

無關的評論:建議您在編寫C ++代碼時養成使用nullptr而不是NULL的習慣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM