Hello!
i am creating a doubly linked list that will store strings, for example:
one two three four five six seven
and i want to delete one of the words when given the position, i have a function that i used for my single linked list and i want to use it as well but i cant get it to work, i think what i need is to point the node in front of the deleted one to the one previous to the deleted one
here is my node defn:
1 2 3 4 5 6 7 8 9 10
struct node{
string data;
node* next;
node* prev;
};
node* head; //first element from left to right (global)
node* tail; // last element from left to right (global)
and here is the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void deleteNode(int n){
struct node* temp1 = head;
if (n == 1){
head = temp1->next;
free(temp1);
return;
}
for (int i = 0; i < n - 2; i++)
temp1 = temp1->next; //temp1 points to (n-1)th node
struct node* temp2 = temp1->next; //nth node
temp1->next = temp2->next; //(n+1)th node
free(temp2); //delete temp2;
}
You can't use the same remove() for both kinds of lists.
The remove() of a doubly linked list has to turn this:
A <-> B <-> C
into this:
A <-> C
If you use the remove() for singly linked lists, you'll instead get this:
A -> C
A <- B <-> C
C still points to B rather than to A, so when you free() B, C will point to invalid memory.