dimanche 20 octobre 2019

How to append a linked list to itself?

Considering that this is my function:

void append(const LinkedList &other){
for (Node *temp = new Node(*head); temp != nullptr; temp = temp -> next){
  Node *ptr = other.head;
  Node *temp2 = new Node;
  temp2 -> value = temp -> value;
  while (ptr -> next != nullptr){
    ptr = ptr -> next; 
    }
  ptr -> next = temp2;
  temp2 -> next = nullptr;
}
return;
} 

where my goal is to append a linkedlist to itself, I do not know exactly what goes wrong. If, for example, I have a linkedlist called n in the main function, where I then declare:

n.append(n);

meaning that &other is going to be pointing at the same node as n, I figured that I would make a new node and deep copy the contents of n.

However, my two outputs are either that I end up in an infinite loop, or that some node ends up getting skipped.

How do I fix this issue?

Aucun commentaire:

Enregistrer un commentaire