简体   繁体   中英

Appending Node Doubly Linked List

I'm trying to append node's to a new list. The program crashes at the while loop.

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++;
  }
 }
}

I've also tried using this instead of that while loop, same result however:

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

Any help would be greatly appreciated!

Edit: Changed the second case above to

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

It got through the entire thing and then displayed characters of other languages, along with symbols, etc - then followed by about every folder on my surface until it finally crashed :c

You currently loop until temp is NULL. When it has reached this calue, you dereference it by doing temp->next . That's UB and is here the cause for your program crash.

Change you while loop as follows, in order to stop when you're at the last element (ie the next element is NULL):

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

Note that there's no risk that temp is NULL at the beginning of the loop, thanks to your if-clause.

Unrelated remark: I recommend that you take the habit of using nullptr instead of NULL when writing C++ code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM