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

标签 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;
    }
}

最佳答案

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

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

关于C++链表——析构函数实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30380209/

相关文章:

c++ - 双端列表

c++ - 带有模板关键字的伪析构函数调用

c - 制作链表时出现Segmentation fault (core dumped)错误

c++ - 为什么析构函数在被删除时调用,而在未删除时不调用?

c++ - 静态存储持续时间对象的破坏和未定义的行为

c++ - 使用winapi计算按钮大小

c++ - 混合 C 和 C++ 代码时出现链接错误

c++ - 使用意外声明为函数的对象后解释 GCC 错误

C++ STL 低级编程

c - C语言实现双向链表