0

I'm working on learning linked lists and I've written a program with various functions to create and manipulate the list, one of them being:

void DeleteNode(int x) {
    struct Node* temp = head;
    struct Node* prevptr = temp->prev;
    struct Node* nextptr = temp->next;
    if(temp == NULL) return;

    while(temp->data != x) {
        temp = temp->next;
    }
    prevptr->next = temp->next;
    nextptr->prev = temp->prev;
    free(temp);
}

When I run my main function:

int main() {        
    InsertAtHead(2); Print(); 
    InsertAtHead(1); Print();
    InsertAtTail(3); Print();
    InsertAtTail(4); Print();
    DeleteNode(3); Print();
}

The output looks like:

Forward: 2 
Forward: 1 2 
Forward: 1 2 3 
Forward: 1 2 3 4 
Segmentation fault (core dumped)

I imagine this means that I've lost the list somewhere in the process of trying to delete a node but can't figure out how. What am I doing wrong here?

5
  • prevptr = temp->prev; : prevptr is NULL. .. prevptr->next = temp->next; : NULL->next might occurs seg-fault. Also while(temp->data != x) { --> while(temp && temp->data != x) { Commented Jul 9, 2017 at 0:23
  • Possible duplicate of How to delete node from linked list? Commented Jul 9, 2017 at 0:26
  • This link illustrate deleting Node from a Linked list geeksforgeeks.org/linked-list-set-3-deleting-node Commented Jul 9, 2017 at 0:27
  • You're right BLUEPIXXY, it's because prevptr was pointing to NULL. Thanks Commented Jul 9, 2017 at 0:30
  • I once did a nice a example for double linked lists: pastebin.com/mScMkkdy Commented Jul 9, 2017 at 0:31

1 Answer 1

0
struct Node* prevptr = temp->prev;

this might be the reason your program is messing up. once you set temp = head, you set the temp node equal to the first node. unless it is a doubly circular linked list, then the first node should not have a prev ptr. Also you arent sending the head node or returning the head node. You are setting temp equal to a random structure called head without letting the function know what head is.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, what happens if the list does not contain x? Also, avoid equivocation in answering questions, there is no "might* about what the code execution will be in this case.
in the above code you are searching for a node to be deleted. You are identifying that node by its value. X is just a variable you set to compare the nodes value too in order to determine if it is the correct node to be deleted. If there is no node with the value that is equal to x, then that means that no node contained that value and therefor cant be deleted because it does not exist in the list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.