C++ : Help needed to debug generic linked list

标签 c++

下面是我对链表的通用表示的尝试,其中我传递了一个整数示例。我知道问题出在我接下来如何分配(通过 add_to_list 函数),但在盯着屏幕 2 小时后,我仍然不知道哪里出了问题。有人可以指导我完成它吗?

#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();

关于C++ : Help needed to debug generic linked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285536/

相关文章:

c++ - 不能用boost编译?

c++ - C++ 中的表表示

c++ - 以 "simple"形式获取 RSA key

c++ - 溢出值在 Arduino 上打印非溢出值

c++ - 无法编译 brian gladman aes 库

c++ - 如何在 C++ 中修复 "Segmentation fault(core dump)"?

c++ - 不同非类型模板参数的不同成员函数

c++ - 用户定义转换中的模板参数类型推导

c++ - 重写代码: Output from file to char* ~> is FILE* to virtual file in RAM possible?

C++ 内存分配。矩阵