【问题标题】:C++ Linked list - destructor implementationC++ 链表 - 析构函数实现
【发布时间】:2015-08-03 12:04:34
【问题描述】:

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

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

【问题讨论】:

  • 好吧,问题本身是在Delete()中你正确删除了一个元素,然后再次设置头部并在析构函数中调用while(head),而不是说if(head)...但是为什么地狱是head STATIC?
  • 想知道列表的起点在哪里?
  • 现在想一想,如果你想拥有两个独立的相同T的列表会发生什么。
  • 他们会有相同的“开始”吗?我认为这将是仅在一个列表中的开始。 Lista* A0 = 新 Lista; Lista* A1 = 新 Lista;那么A1头和A0头会一样吗?
  • 是的,这就是static 的意思。无论如何,要解决它,您要做的就是开设一个像class list { node* head; struct node{ node* prev, T item, node* next } 这样的课程,然后从那里开始。

标签: c++ linked-list destructor


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 2013-09-12
    • 2019-04-09
    • 2013-04-26
    • 2017-09-13
    • 1970-01-01
    • 2020-10-07
    • 2021-07-20
    相关资源
    最近更新 更多