C++:调试通用链表所需的帮助
C++ : Help needed to debug generic linked list
下面是我对链表的泛型表示的尝试,其中我传递了一个带有整数的示例。我知道问题出在我如何分配下一个(通过add_to_list函数),但在盯着屏幕看了两个小时后,我仍然不知道出了什么问题。有人能引导我通过吗?
#include<iostream>
using namespace std;
/** Class Definition here */
template<typename T>
class Linklist
{
struct node
{
node(T value,node* next=NULL):value(value),next(next) {}
node* next;
T value;
};
node* head;
node* curr;
public:
Linklist(node* n=0):head(n) {}
~Linklist();
void add_to_list(T value, bool x=1);
void print();
};
/** Class destructor */
template<typename T>
Linklist<T>::~Linklist()
{
node *ptr ;
while(head!=NULL)
{
ptr=head;
head=head->next;
delete ptr;
}
}
template <typename T >
void Linklist<T>::add_to_list(T x, bool z)
// bool basically means if to add the element to beginning or end of list, 1 for end.
{
node* k=new node(x);
if(head==NULL)
{
k->value=x;
k->next=NULL;
head=curr=k;
}
else
{
k->value=x;
k->next=NULL;
if (z==1)
{
curr->next=k;
curr=k;
}
else
{
k->next=head;
head=k;
}
}
delete(k);
}
template<typename T>
void Linklist<T>::print()
{
node* ptr= new node(1);
ptr=head;
if (ptr==NULL)
{
return ;
}
else
{
cout<<"reached here n " <<"pointer is"<<ptr->value<<"n next is"<<ptr->next;
while(ptr!=NULL)
{
cout<<ptr->value<<"-->";
ptr=ptr->next;
}
}
}
int main()
{
Linklist<int> *intlist=new Linklist<int>();
intlist->add_to_list(20,0);
intlist->add_to_list(344,1);
intlist->print();
return 0;
}
将delete(k);
添加到列表后,系统可以将内存用于新对象。你不应该删除它,因为你仍然在使用内存
当你不删除它时,输出是:
reached here
pointer is20
next is0020882020-->344-->
与错误无关,但您应该尽可能避免new
,例如您的main
代码:
Linklist<int> intlist;
intlist.add_to_list(20,0);
intlist.add_to_list(344,1);
intlist.print();
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 我需要一些帮助来理解一些涉及C++链表的代码
- 需要帮助,需要计算链表中负值的数量,C++
- C ++链表奇怪的帮助
- 尝试在链表程序的末尾进行更简单的插入.小问题需要帮助
- C++帮助-从链表中泄漏数据和分段错误
- C++:调试通用链表所需的帮助
- 请帮助我理解链表c++中的运算符重载=
- c++链表节点计数(需要帮助)
- 需要帮助编码迭代器的循环链表在c++
- c++链表帮助(指针)
- 如何使用析构函数清除链表内存,而不会出现valgrind错误?[更新:操作员过载帮助]
- 帮助C++中的双重链表
- 链表需要帮助无法打印我的数据.想要添加功能.在 C - C++ 中
- 双重链表的帮助
- 帮助使用链表模板