问题描述
#include <iostream>
using namespace std;
template<class T>class LinkedList
{
public: T* current;
public: LinkedList* next = NULL;
public: LinkedList* prev = NULL;
private: long long CountFirst()
{
if (prev == NULL)
{
return 0;
}
long long answer = (prev == NULL)?0:prev->prev->CountFirst();
return answer;
}
public: long long Count()
{
if (next == NULL)
{
return 0;
}
long long answer = CountFirst();
answer += (current == NULL)?0:1;
answer += (next == NULL)?0:next->Count();
return answer;
}
public: T* Find()
{
}
public: T& operator[](int index)
{
if (next == NULL and current != NULL)
{
return *current;
}
if (prev->Count() - 1 > index)
{
return *prev[index].current;
}
if (prev->Count() == index)
{
return *current;
}
return *next[index - prev->Count()].current;
}
public: void Add(T ForAdd, int pos)
{
cout << "ADD";
((*this)[pos - 1]) = (*this)[pos];
cout << "ADD";
((*this)[pos]) = (*this)[pos - 1];
cout << "ADD";
((*this)[pos]) = (*this)[pos + 1];
cout << "ADD";
((*this)[pos + 1]) = (*this)[pos];
cout << "ADD";
((*this)[pos]) = &ForAdd;//crash
cout << "ADD";
}
public: void Delete(int pos)
{
(*this)[pos - 1] = (*this)[pos + 1];
(*this)[pos + 1] = (*this)[pos - 1];
}
};
它在功能上崩溃添加
it crashes on function Add
推荐答案
public: void Add(T ForAdd, int pos)
{
...
((*this)[pos]) = &ForAdd;//crash
}
您正在获取参数ForAdd的地址,该地址是按值传输的,因此只是一个临时变量从函数返回后立即超出范围。你正在将这个地址分配给你链接列表的当前指针。
除此之外我还看到很多其他奇怪的东西。
- 成员next和prev无处分配,所以你的列表只包含一个元素
- 缺少构造函数所以所有成员都没有初始化
- 你不要在列表和列表的节点之间进行区分,并且正在尝试使用相同的类来支持
- CountFirst函数是递归定义的(绝对没有用)更长的列表)并且因为它将代表访问prev-> prev->这太过分了。你忘了添加1,因此如果没有先崩溃,CountFist将总是返回0。
我可以在这里继续一段时间。你为什么不看看其他链表的实现并从中学习。这将使您的生活更轻松,您的学习进度将更快。
You are taking the address of the parameter ForAdd, which is transferred by value and hence just a temporary variable that will go out of scope as soon as you return from the function. And you are assing this address to the current pointer of you linked list.
Besides that I see many other strange things.
- the members next and prev are nowhere assigned to, so your list will only contain a single element
- the constructor is missing so all the members are not initialized
- you don't distiguish between the list and a node of the list and are trying to use the same class for both
- the CountFirst function is defined recursively (an absolute no go for longer lists) and as it stands will access prev->prev-> which is one step too much. You forgot to add 1 and hence CountFist will always return 0 if doesn't crash first.
I could continue for a while here. Why don't you take a look at the implementation of other linked lists and learn from them. That will make your life a lot easier and your learning progress will be a lot faster.
这篇关于链表帮助C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!