c++链表析构函数实现

C++ Linked list - destructor implementation

本文关键字:实现 析构函数 链表 c++      更新时间:2023-10-16

我不知道如何为我的链表实现创建析构函数。我试过这样做:

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 << "Errorn";
    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;
}