gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:15:41 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com