双重链接列表



我在PopAtEnd中遇到分段故障,有人能帮我解决吗

#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node* prev;
};
Node* head = NULL;
Node* last = NULL;

void InsertAtBeg(int ele){
Node* ptr = new Node();
ptr->data = ele;
if(head == NULL && last == NULL){
head = last = ptr;
ptr->next = NULL;
ptr->prev = NULL;
return;
}
ptr->prev = NULL;
ptr->next = head;
head = ptr;
}
void InsertAtEnd(int ele){
Node* ptr = new Node();
ptr->data = ele;
last->next = ptr;
ptr->next = NULL;
last = ptr;
}
void PopAtBeg(){
Node* temp = head;
head = head->next;
head->prev = NULL;
delete temp;
}
//**Segmentation Fault**//
void PopAtEnd(){
Node* temp = last;
last = last->prev;
last->next = NULL;
delete temp;

}
void display(){
Node* temp = head;
int i = 0;
while(temp->next != NULL){
cout << temp->data <<" ";
temp = temp->next;
i++;
}
cout<<temp->data<<endl;
cout<<"Size of the list is "<<i + 1<<endl;
}
void search(int key){
Node* temp = head;
int  i = 0;
while(temp->next != NULL){
if(temp->data == key)
cout<<key<<" is found at index "<<i<<endl;
temp = temp->next;
i++;
}
}
int main()
{
InsertAtBeg(7);
InsertAtBeg(2);
InsertAtBeg(9);
InsertAtEnd(1);
InsertAtEnd(3);
cout<<"The linked list is : ";
display();
search(9);
search(1);
PopAtBeg();
PopAtEnd();
cout<<"The linked list is : ";
display();
}

提前感谢您的帮助。

正如user4581301所说,您必须在所有位置设置prev,以免保持为null。例如,在PopAtEnd()中导致分段错误的原因是您说last = last->prev;last->prev为NULL。因此,您必须在last = ptr;之前的InsertAtEnd()中添加此行:ptr->prev = last;

相关内容

  • 没有找到相关文章

最新更新