C ++链表 - 析构函数实现

时间:2015-05-21 17:10:01

标签: c++ linked-list destructor

我不知道如何为我的链表实现创建析构函数。我尝试过类似的东西:

template <class T>
Lista<T>::~Lista()
{
    while (head) Delete(); 
}   

但是当我只想删除一个元素时它正在删除所有列表。有解决方案吗也许在静态领域保持头脑是错误的?

#pragma once
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

template <class T>
class Lista
{
private:
    Lista *next;
    T data;
    static Lista *head;

public:
    Lista();
    void Delete();  //to delete
    void Delete2(Lista *);  //just for testing
    void Delete_wyb(int);   //to delete selected
    int Add(T data);    //to add
    T Pobierz(int which);   //to return data
    void Sortuj();  //to sort
    int Ile();  //how many elements

    ~Lista();
};

.cpp摘录

#include "Lista.h"

template<class T>
Lista<T>* Lista<T>::head = NULL;

template <class T>
Lista<T>::Lista()
{
}

template <class T>
void Lista<T>::Delete()
{
    if (head == NULL) cout << "Error\n";
    else
    {
        Lista *tmp = head;
        head = head->next;
        delete tmp;
    }
}

template <class T>
void Lista<T>::Delete_wyb(int choice)  //deletes by choice
{
    Lista *tmp;
    Lista *tmp2;
    int licznik = 0; //licznik is just for counting
    int licznik2 = 0;

    if (licznik == choice) Delete(); 
    else
    {
        tmp2 = head;

        for (; licznik != choice; licznik++)
        {
            tmp2 = tmp2->next;
        }

        tmp = head;

        for (; licznik2 != choice - 1; licznik2++)
        {
            tmp = tmp->next;
        }

        tmp->next = tmp2->next;
        delete tmp2;
        tmp2 = NULL;
    }
}

template <class T>
int Lista<T>::Add(T data) 
{
    Lista *tmp;
    tmp = new Lista;

    if (tmp == NULL) return 0;
    else
    {
        tmp->data = data;
        tmp->next = head;
        head = tmp;

        return 1;
    }
}

1 个答案:

答案 0 :(得分:1)

您需要更新head指针并删除元素:

while (head)
{
  Lista * temp = head;
  head = head->next;
  delete temp;
}