Segmentation fault during deleting a node from the end of doubly linked list

时间:2019-01-09 21:40:05

标签: c++ data-structures doubly-linked-list

I am trying to delete a node from the end of the doubly linked list,but i am getting:

segmentation fault

i have added different functions to add the node, from beginning , from end , and at any position.I checked the insertion of nodes,its working fine,the DLL is displayed correctly,but when it comes to deleting function,it gives segmentation fault.

struct Node {
    Node* left;
    Node* right;
    int data;
};
Node* head = NULL;
void insertion_At_End(int element) {
    Node* ptr = head;
    Node* temp = new Node;
    temp->left = temp->right = NULL;
    temp->data = element;
    if(head==NULL) {
        head = temp;
    } else {
        while(ptr->right!=NULL) {
            ptr = ptr->right;
        }
        temp->left = ptr->right;
        ptr->right = temp;
    }
}
void insertion_At_Beg(int element) {
    Node* ptr = head;
    Node* temp = new Node;
    temp->left = temp->right = NULL;
    temp->data = element;
    if(head==NULL) {
        head = temp;
    } else {
        temp->right = ptr;
        ptr->left = temp;
        head = temp;
    }
}
void insertion_At_Pos(int element , int position , int length) {
    Node* ptr;
    Node* temp = new Node;
    temp->left = temp->right = NULL;
    temp->data = element;
    int counter = 1;
    if(position==1) {
        insertion_At_Beg(element);
    }
    else if(position==length) {
        insertion_At_End(element);
    }
    else {
        ptr = head;
        while(counter!=(position-1)) {
            ptr = ptr->right;
            counter++;
        }
        temp->right = ptr->right;
        ptr->right->left = temp;
        temp->left = ptr;
        ptr->right = temp;
    }
}
void deletion_At_End() {
    Node *ptr = head;
    while(ptr->right!=NULL) {
        ptr = ptr->right;
    }
    ptr->left->right=NULL;
    delete ptr;
}

1 个答案:

答案 0 :(得分:0)

如果列表中只有一个元素,则会出现错误。当列表中只有一个元素时,由于它不存在,因此无法将其左侧的内容设置为NULL。这对我有用:

void deletion_At_End() {
  Node *ptr = head;

  while(ptr->right!=NULL) {
      ptr = ptr->right;
  }
  if(ptr->left == NULL){
      delete ptr;
  }
  else{
      ptr->left->right=NULL;
      delete ptr;
  }

}