0

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

1 回答 1

5

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();
于 2013-08-17T05:49:16.663 回答