C++中的单向链表
One-way linked list in C++
我开始研究算法和数据结构。我决定尝试一下单向链表。它包含诸如在所选元素之后插入元素,删除具有给定值的元素并返回已删除项目数量的函数,返回列表和类的当前内容的函数以写入和读取文件。功能有一个小问题,必须添加新元素。调试器返回以下错误:
在 AiSD.exe 中0x00e71ea2的首次机会异常:0xC0000005:访问冲突读取位置0x00000000。
在 AiSD.exe 中0x00e71ea2处未处理的异常:0xC0000005:访问冲突读取位置0x00000000。
看起来像指针的问题,但我不知道如何解决它。这不是我现在的专长...还!所以我请你帮我。有一个代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
struct Node
{
Node *next;
int key;
};
class List
{
public:
Node *head;
unsigned int counter;
List()
{
head = NULL;
counter = 0;
}
unsigned size(Node *p)
{
unsigned int c=0;
while(p)
{
c++;
p = p->next;
}
return c;
}
void Addafter(Node *e, int v)
{
Node *p = new Node;
p->next = e->next; //there's a problem
p->key = v;
e->next = p;
}
int Delete(int v)
{
Node *p = new Node;
int count = 0;
while(p->next != NULL)
{
if(p->key = v)
{
delete p;
count++;
return count;
}
}
}
void Write()
{
string data;
fstream file;
file.open("D:\plik2.txt", ios::out);
Node *p = head;
while(p->next != NULL)
{
p = p->next;
int wartosc = p->key;
file<<wartosc;
}
file.close();
}
void Read()
{
string data;
fstream file;
file.open("D:\plik.txt", ios::in);
Node *p = head;
for(int i=0; i<counter; i++)
{
getline(file, data);
int result = atoi(data.c_str());
p->key = result;
p = p->next;
}
file.close();
}
};
int main()
{
List a;
a.Read();
a.Addafter(a.head, 3);
a.Delete(5);
a.size(a.head);
system("PAUSE");
return 0;
}
当你
输入 AddAfter 方法时,a.head 是 NULL。所以发生的事情是:
addAfter(Node *e /*Null in this case*/, int v) {
Node *p = new Node; // Ok.
p->next = e->next; // It is equivalent to p = NULL->next Which just segfaults.
}
在这种情况下,您可能想要执行以下操作:
addAfter(Node *e /*Null in this case*/, int v) {
Node *p = new Node;
p->key = v;
if (e) {
p->next = e->next;
e->next = p;
}
else {
e = p;
e->next = NULL;
}
}
每当你做链表时,拿出一张纸,一步一步地画出你的代码正在做什么(小框和箭头很好地表示链表,让你把它布置出来,这样人眼就可以理解/看到。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表,将列表复制到另一个列表
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 对单向链表进行排序时出现运行时错误