【问题标题】:Doubly LinkedList双链表
【发布时间】:2021-09-25 13:41:17
【问题描述】:

我在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();

}

提前感谢您的帮助。

【问题讨论】:

  • 您实际上并没有实现双向链表,而是全局命名空间中的一堆静态函数,对两个静态指针变量执行操作。我真的怀疑这个分段错误会是唯一的问题(你可以阅读静态/全局变量的行为),但是将这些函数包装在一个类中将是一个好的开始。
  • 您的main 程序应该小得多。您应该最多插入 2 个节点,看看是否可以删除最后一个。如果它不适用于 2 个节点,则它不适用于 5 个节点。然后你应该能够调试你的代码,用最少的数据来查看哪里出了问题。
  • 通过画图帮助自己想象问题。然后检查你的代码(最好在调试器的帮助下,因为它会告诉你是否对一行代码应该做什么做出了错误的假设)并尝试绘制相同的图片。如果你不能,你会很清楚错误在哪里,因为它是图片偏离的地方。
  • 看看你设置的所有地方prev。你会发现除了NULL,你从来没有将它设置为任何东西。与your Rubber Duck讨论你为什么这样做
  • PopAtEnd() 中的哪一行触发了分段错误?那时你的变量的值是多少?

标签: c++ data-structures segmentation-fault computer-science doubly-linked-list


【解决方案1】:

正如 user4581301 所说,您必须在任何地方设置 prev 才能保持为空。例如,在PopAtEnd() 中导致分段错误的原因是您说last = last-&gt;prev;last-&gt;prev 为NULL。所以,你必须添加这一行:ptr-&gt;prev = last; in InsertAtEnd() before last = ptr;

【讨论】:

  • 当然,永远不要忘记与你的橡皮鸭讨论这个问题! very important
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多