我正在尝试实现链表。类insertLast()
中的方法linkedListType
之一导致错误
这里是linkedList.hpp
文件中的功能
template<class dataType>
void linkedListType<dataType>::insertLast(dataType data)
{
nodeType<dataType> *newNode = new nodeType<dataType>();
newNode->info =data;
if (first==NULL) insertFirst(data);
else{
newNode->link=NULL;
last->link=newNode;
last=newNode;
}
}
template<class dataType>
void linkedListType<dataType>::destroyList()
{
nodeType<dataType> *temp;
while(first!=NULL){
temp = first;
first=first->link;
delete temp;
}
last=NULL;
count=0;
}
template<class dataType>
void linkedListType<dataType>::insertFirst(dataType data)
{
nodeType<dataType> *newNode = new nodeType<dataType>();
newNode->info=data;
if (first==NULL){
first=newNode;
last=newNode;
}
else{
newNode->link=first;
first=newNode;
}
}
这里是main
功能
#include <iostream>
#include "linkedList.hpp"
using namespace std;
int main()
{
linkedListType<string> names;
int numOfNames;
cout<<"\nEnter the number of names: ";cin>>numOfNames;
string name;
for(int i=0; i<numOfNames;i++) {
cin>>name;
names.insertLast(name);
}
names.destroyList();
}
当我使用命令时:
valgrind --leak-check=full ./a.out
==5528== Command: ./a.out
==5528==
Enter the number of names: 2
xyv
fds
==5528==
==5528== HEAP SUMMARY:
==5528== in use at exit: 40 bytes in 1 blocks
==5528== total heap usage: 6 allocs, 5 frees, 74,872 bytes allocated
==5528==
==5528== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==5528== at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5528== by 0x108F45: linkedListType<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::insertLast(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/abdo/cpp/linkedList/a.out)
==5528==
==5528== LEAK SUMMARY:
==5528== definitely lost: 40 bytes in 1 blocks
==5528== indirectly lost: 0 bytes in 0 blocks
==5528== possibly lost: 0 bytes in 0 blocks
==5528== still reachable: 0 bytes in 0 blocks
==5528== suppressed: 0 bytes in 0 blocks
==5528==
==5528== For counts of detected and suppressed errors, rerun with: -v
==5528== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
它给我一个错误,所以我的代码有什么问题吗?
您需要更改insertLast
功能:
template<class dataType>
void linkedListType<dataType>::insertLast(dataType data)
{
if ( !first ) insertFirst( data );
else
{
nodeType<dataType> *newNode = new nodeType<dataType>();
newNode->info =data;
newNode->link=NULL;
last->link=newNode;
last=newNode;
}
}