C++:调试通用链表所需的帮助

C++ : Help needed to debug generic linked list

本文关键字:帮助 链表 调试 C++      更新时间:2023-10-16

下面是我对链表的泛型表示的尝试,其中我传递了一个带有整数的示例。我知道问题出在我如何分配下一个(通过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();