今天我在LinkedList中练习删除一个节点实现,结果出现了这个问题。这是我的LinkedList.h文件:
#pragma once
template <class Data>
class Node
{
public:
Node();
Node(Data newData, Node<Data>* newNext);
~Node();
Node<Data>* next;
Data data;
};
template<class Data>
class LinkedList
{
public:
LinkedList();
~LinkedList();
int size();
bool put(Data data,int pos);
bool del(int pos);
void show();
private:
typedef Node<Data>* nodePtr;
nodePtr head;
int N;
bool isEmpty();
nodePtr getPosition(int pos);
};
然后我的LinkedList.cpp文件:
#include <iostream>
#include "LinkedList.h"
using namespace std;
template<class Data>
Node<Data>::Node() {
next = NULL;
}
template<class Data>
Node<Data>::Node(Data newData, Node * newNext)
{
data = newData;
next = newNext;
}
template<class Data>
Node<Data>::~Node()
{
delete next;
}
template<class Data>
LinkedList<Data>::LinkedList() {
head = NULL;
N = 0;
}
template<class Data>
LinkedList<Data>::~LinkedList()
{
delete head;
}
template<class Data>
int LinkedList<Data>::size()
{
return N;
}
template<class Data>
bool LinkedList<Data>::isEmpty()
{
return N == 0;
}
template<class Data>
Node<Data>* LinkedList<Data>::getPosition(int pos)
{
nodePtr temp = head;
if (pos > N-1) pos = N-1;
for (int i = 0; i < pos; i++)
temp = temp->next;
return temp;
}
template<class Data>
bool LinkedList<Data>::put(Data data, int pos)
{
nodePtr add;
if (pos == 0) {
add = new Node<Data>(data, head);
head = add;
}
else{
nodePtr pPre = getPosition(pos-1);
nodePtr pCur = pPre->next;
add = new Node<Data>(data, pCur);
pPre->next = add;
}
N++;
return true;
}
template<class Data>
bool LinkedList<Data>::del(int pos)
{
if (isEmpty()) return false;
if (pos == 0) {
nodePtr pTemp = head;
head = head->next;
delete pTemp; //error
}
else {
nodePtr pPre = getPosition(pos - 1);
nodePtr pCur = pPre->next;
pPre->next = pCur->next;
delete pCur; //error
}
N--;
return true;
}
template<class Data>
void LinkedList<Data>::show()
{
for (nodePtr pTemp = head; pTemp != NULL; pTemp = pTemp->next)
cout << pTemp->data;
}
void main() {
LinkedList<int> list;
list.put(0, 0);
list.put(1, 0);
list.put(2, 0);
list.put(3, 0);
list.put(4, 0);
list.del(0);
list.show();
}
如果我注释这些行,程序就会工作(但我认为这会导致内存泄漏),如果我让这些行在那里,它会导致"程序停止工作"和控制台窗口中的随机数。所以你们能帮助我如何正确删除这些指针吗?很抱歉之前的问题不明确。抱歉我英语不好。
哦,我刚刚认错了。因为我的~Node()方法:
template<class Data>
Node<Data>::~Node()
{
delete next;
}
因此,当我删除一个Node时,它会删除它在一行中链接到的所有指针,从而导致该错误。不管怎样,谢谢你们的帮助。