C++ 程序中双链表的未处理异常

Unhandled exception in c++ program for doubly linked list

本文关键字:未处理 异常 链表 程序 C++      更新时间:2023-10-16

我在Visual Studio 2013中为双向链表编写了一个程序,它在标有注释的行中抛出了未处理的异常错误: -

linked_list_double.h: -

#pragma once
#include<iostream>
template <typename T>
struct Node
{
    T data;
    Node *next, *prev;
};
template <typename T>
class doubleLinkedList
{
private:
    Node<T> *top;
public:
    doubleLinkedList()
    {
        top = nullptr;
    }
    void add(T data)
    {
        Node<T> *temp = new Node<T>;
        temp->prev = nullptr;
        temp->next = top;
        top->prev = temp;     //unhandled exception here
        top = temp;
    }
    void display()
    {
        Node<T> *temp;
        temp = top;
        std::cout<<"nullptr<--->n";
        while(temp)
        {
            std::cout<<temp->data<<"<--->";
            temp = temp->next;
        }
        std::cout<<"nullptrn";
    }
};

主.cpp: -

#include "linked_list_double.h"
int main()
{
    doubleLinkedList<int> L;
    L.add(3);
    L.add(4);
    L.display();
    return 0;
}

错误是:-

Unhandled exception at 0x011C4B79 in dataStructures2.exe: 0xC0000005: Access violation writing location 0x00000008.

我以前从未写过双向链表。我不确定程序中是否有任何逻辑错误。任何帮助都将不胜感激。

top

第一次添加时为空。 因此,任何在 null 时top尊重的尝试都会崩溃。

所以取而代之的是:

    top->prev = temp;     //unhandled exception here

这样做:

if (top != nullptr)
{
   top->prev = temp;
}