c++链表析构函数实现
C++ Linked list - destructor implementation
我不知道如何为我的链表实现创建析构函数。我试过这样做:
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;
}
相关文章:
- 如何在 CRTP 中实现析构函数?
- 如何使用指针向量实现类析构函数 C++.
- 使用shared_ptr时需要实现析构函数、复制构造函数、赋值运算符
- 当声明了虚拟析构函数但没有实现时会发生什么情况
- 如何实现在构造函数中使用自身的对象的析构函数
- 如何实现纯虚拟析构函数
- C++ 链接列表队列实现和析构函数错误:"Aborted (Core Dumped)"
- 为什么纯虚拟析构函数需要实现
- GoogleMock让我在mock类中实现析构函数吗
- 根据析构函数和移动构造函数实现移动赋值
- 重写默认构造函数/析构函数而不实现它们
- G++ 警告,缺少纯虚拟析构函数的实现
- C++ 抽象类是否应该为(虚拟)析构函数提供实现
- 静态字段的析构函数.辛格尔顿实现
- 当在头文件上而不是在CPP文件上实现时,析构函数会导致内存泄漏——仅在linux上实现
- 生产编译器如何在流控制上实现析构函数处理
- 为什么我们没有义务实现纯虚析构函数
- 单链表-由于析构函数实现导致的分段错误
- 使用D_ptr实现析构函数
- 实现析构函数