删除链接列表的节点时发生运行时错误

时间:2016-10-12 10:23:34

标签: c++

这是我的简单结构化链接列表的C ++代码。

#include <iostream>
using namespace std;

class Node{
public:
    int data;
    Node* next;
    Node* prev;
    Node(){
        data=-1;
        next=NULL;
        prev=NULL;
    }
    Node(int d,Node *nnext){
        data=d;
        next=nnext;
    }
    void add(Node* nnext){
        next=nnext;
        nnext->prev=this;
    }

};
void print(Node*  head){
    Node* cNode;
    cNode=head;
    while (cNode!=NULL){
        cout <<"["<<cNode->data<<"]" << endl;
        cNode=cNode->next;
    }
}
void insertAfter(Node* pNode, Node* nNode){
    nNode->next = pNode->next;
    pNode->next = nNode;
    pNode->next->prev = nNode;

}
void deleteNode(Node* b){

    Node* c=b->next;
    Node* a=b->prev;
    a->next=c;
    c->prev=a;
    delete b;

}
void main(){
    Node* head;
    head=new Node();
    head->data=1;
    Node * currentNode=head;
    for (int i=2;i<=5;i++){
        Node* nNode=new Node(i,NULL);
        currentNode->add(nNode);
        currentNode=nNode;
    }
    cout << currentNode->data << endl;
    print(head);
    insertAfter(head, new Node(99,NULL));
    //deleteNode(currentNode);
    print(head);

}

案例检查是不必要的,因为我只需要链接列表的概念。如果您有其他版本的这类简单链接列表代码,请告诉我们!谢谢!

2 个答案:

答案 0 :(得分:2)

您的deleteNode()函数不会检查ca是否为非NULL,但会立即取消引用它们。这意味着如果您尝试删除列表的第一个或最后一个节点,程序将崩溃。

您的insertAfter()函数也会按错误的顺序设置指针,导致nNode->prev指向自身。

答案 1 :(得分:1)

当你删除&#34; head&#34;你的deleteNode函数没有处理这种情况。元件。

让我们以此列表为例:

头 - &gt; n1 - &gt; n2 - &gt; n3(每个节点也有一个指向它之前的节点的链接,就像你在代码中所做的那样)

如果您调用deleteNode(head),将发生以下情况:

Node* c=b->next;  // b = head, c = head.next = n1
Node* a=b->prev;  // b = head, a = head.prev = NULL
a->next=c;        // a = NULL, then NULL->next

您无法访问NULL对象的变量,这就是您收到运行时错误的原因。

P.S:如果你想提高对数据结构的理解,我建议你这本书:https://mitpress.mit.edu/books/introduction-algorithms

相关问题