I'm working on a doubly linked list and want to implement an insert() function at a given index. Right now I am able to traverse through the linked list with a for loop. However, I want execute the traversing with a while loop but I cant figure it out.
The for loop I am running is
for (int i = 0; i < index - 1; i++) {
//move the temp pointer down the list
temp = temp->next;
}
The full insert() function:
template<typename Data>
void Link<Data>::insert(int index, Data value) {
if (head == nullptr) {
Link<Data>::push2Front(value);
}
else if (index >= size) {
Link<Data>::add2Rear(value);
}
else {
Node* temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp->next;
}
Node* nn = new Node;
nn->value = value;
nn->next = temp->next;
nn->prev = temp->prev;
temp->next->prev = nn;
temp->next = nn;
size++;
}
}
Suggestions are much appreciated.