如何解决双向链表
我在我的 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,不要留空。例如,导致 PopAtEnd()
中的分段错误的原因是您说 last = last->prev;
和 last->prev
为 NULL。因此,您必须在 ptr->prev = last;
InsertAtEnd()
中添加此行:last = ptr;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。