I'm trying to make an insert function for a linked list.
It needs to insert at the end of the list and not traverse if the head node is the only node in the list.
if the function receives an "i" that is the same as the index (data) of one of the nodes then it needs to move the node that is already in the list to the end of the list.
This is what I have so far and I'm wondering why this initial while loop doesn't do the unlinking and relinking I need it to.
Any conducive thoughts that can use this already laid out logic would be greatly appreciated!
struct node {
int index;
node *next, *prev;
node(int i, node* n = nullptr, node* p = nullptr)
: index(i), next(n), prev(p) { }
};
void list::insert(int i) {
// Set n to last node in list, or nullptr if list is empty.
// Set x to first matching node found, or nullptr if no match.
node* n = head, *x = nullptr;
if (n) {
for ( ; n->next; n = n->next) if (!x && n->index == i) x = n;
if (!x && n->index == i) x = n;
}
// If a matching node was found, remove it from the list.
if (x) {
if (!x->next) return; // already at end of list
if (x->prev)
x->prev->next = x->next;
else
head = x->next;
x->next->prev = x->prev;
x->next = nullptr;
}
// If no matching node was found, create a new node.
else {
x = new node(i);
++numNodes;
}
// Add the node to the end of the list.
if (n) n->next = x;
else head = x;
x->prev = n;
}
If you need to insert at the end of a list, then it's common to also have a tail pointer as well as a head pointer - especially with a double-linked list (prev, next).