【发布时间】:2018-11-16 21:44:16
【问题描述】:
我是一名初学者,正在研究链接列表。我正在尝试制作一个向列表添加元素、更新列表、显示并删除它的程序。我遇到了一个异常:读取访问冲突。温度为 0xDDDDDDDD。 我认为 display() 函数存在一些问题。调试器也会显示相同的内容。
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
Node::Node() //constructor
{
head = NULL;
}
Node::~Node() //destructor
{
}
void Node::addFirstNode(int n) //adding the first element in the list
{
node *temp = new node;
temp->data = n;
temp->next = NULL;
head = temp;
}
void Node :: addLast(int n) //Adding elements at the end of the list
{
node *last = new node;
last->data = n;
last->next = NULL;
node *temp = new node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = last;
}
void Node::display() //Displaying the list
{
node *temp = head;
while (temp != NULL)
{
cout<<temp->data;
temp = temp->next;
}
}
//the main function:
#include "stdafx.h"
#include "Node.h"
#include<iostream>
using namespace std;
int main()
{
Node a;
a.addFirstNode(101); //Calling function : addFirstNode
a.addLast(102); //Calling function : addLast
a.addLast(103); //Calling function : addLast
a.addLast(104); //Calling function : addLast
a.display(); //Calling function : display
return 0;
}
Node.h文件如下:
struct node
{
int data;
node *next;
};
class Node
{
private :
node *head;
public:
Node();
~Node();
void addFirstNode(int n);
void addLast(int n);
void display();
};
【问题讨论】:
-
您应该查看调用堆栈以找出它发生的原因和位置
-
注意:
node *temp = new node;存在内存泄漏,您分配了一个对象,然后立即通过执行temp = head来倾斜它。同时显示调用它的代码,以便我们确切地知道你在做什么 -
在
Node::addFirst(),temp->next = NULL;应该是temp->next = head; -
但是我希望head等于temp,因此我首先设置了temp节点的数据和next,然后将head等同于temp节点。这不应该工作吗?
-
node.h长什么样子?
标签: c++ linked-list