C++双向链表PopAtEnd函数触发Segmentation fault问题求助
问题排查与修复
核心错误原因
InsertAtEnd插入尾部函数漏给新节点的prev指针赋值,导致所有尾部插入的节点prev为野指针,调用PopAtEnd取last->prev时拿到非法地址,访问last->next直接触发段错误。InsertAtEnd未做空链表判断,若首次调用该函数,last为NULL,访问last->next会直接崩溃。PopAtEnd、PopAtBeg均未处理删除后链表为空的边界场景,也没有做空链表校验,空链表调用或者删到最后一个节点时会触发空指针访问。InsertAtBeg漏给原链表头节点的prev赋值为新节点,双向链表的前驱指向不完整。search函数循环条件仅判断temp->next != NULL,不会匹配链表最后一个节点的数值。display函数没有做空链表判断,空链表调用会直接崩溃。
修复后完整可运行代码
#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->prev = ptr; // 修复:原头节点的prev指向新头节点 head = ptr; } void InsertAtEnd(int ele){ Node* ptr = new Node(); ptr->data = ele; ptr->next = NULL; // 新增空链表判断 if(head == NULL && last == NULL){ head = last = ptr; ptr->prev = NULL; return; } last->next = ptr; ptr->prev = last; // 修复:新节点的prev指向原尾节点 last = ptr; } void PopAtBeg(){ // 新增空链表校验 if(head == NULL) return; Node* temp = head; head = head->next; // 修复:判断删除后链表是否为空,对应处理last指针 if(head != NULL){ head->prev = NULL; }else{ last = NULL; } delete temp; } void PopAtEnd(){ // 新增空链表校验 if(last == NULL) return; Node* temp = last; last = last->prev; // 修复:判断删除后链表是否为空,对应处理head指针 if(last != NULL){ last->next = NULL; }else{ head = NULL; } delete temp; } void display(){ // 新增空链表判断 if(head == NULL){ cout << "空链表" << endl; cout << "Size of the list is 0" << endl; return; } 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 != 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(); return 0; }
内容的提问来源于stack exchange,提问作者Sadiya
相关产品推荐
相关产品推荐

