-
Linkedlist deletion
hey everyone so i was given a task with linked list to delete a specific number in the DOUBLY LINKED LIST but my code is giving an access violation error even after multiple dry runs i cant figure out what is wrong the task basically was to create a search function which finds a specific number in linked list and a deletion function which deletes that specific link
insert
Code:
node* search(int val){
node* cur=head;
while(cur!=NULL){
if(cur->data==val){
cout<<"value found "<<val<<endl;
return cur;
}
cur=cur->next;
}
cout<<"value not exist"<<endl;
return NULL;
}
bool delspval(int val){
node*temp=0;
if(search(val)==NULL){
return 0;
}
else{
temp=search(val);
temp->next->prev=temp->next;
delete temp;
temp=0;
cout<<"specific value "<<val<<" deleted"<<endl;
return 1;
}
}
in the above given code the line "temp->next->prev=temp->next;" is giving the error im pretty much a beginner at linked lists so any help would be appreciated thanks
-
First, learn how to indent code.
Your indentation is all over the place, making your code impossible to follow.
Code:
node *search(int val)
{
node *cur = head;
while (cur != NULL) {
if (cur->data == val) {
cout << "value found " << val << endl;
return cur;
}
cur = cur->next;
}
cout << "value not exist" << endl;
return NULL;
}
bool delspval(int val)
{
node *temp = 0;
if (search(val) == NULL) {
return 0;
} else {
temp = search(val);
temp->next->prev = temp->next;
delete temp;
temp = 0;
cout << "specific value " << val << " deleted" << endl;
return 1;
}
}
Second, Doubly linked list - Wikipedia
The first and last nodes of a double linked list are special, you need to take this into account.
-
Nitpick
Code:
bool delspval(int val)
{
node *temp = 0;
if (search(val) == NULL) {
return 0;
} else {
temp = search(val);
temp->next->prev = temp->next;
delete temp;
temp = 0;
cout << "specific value " << val << " deleted" << endl;
return 1;
}
}
You want to search through the list only once....normally.