我的程序正在编译,但当我尝试运行此代码时遇到了seg错误。我想做的是将一个元素附加到链表的末尾。以下是我的应用程序正在做的事情:
int main()
{
linklist<int> l;
int i = 30;
l.insertEnd(i);
return (0);
}
下面是我的类中函数的实现:
template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer = NULL)
{
headPointer = new node(anItem, NULL);
}
else
{
node* endPointer = headPointer;
while(endPointer->linkPointer != NULL)
{
endPointer = endPointer->linkPointer;
}
endPointer->linkPointer = new node(anItem, NULL);
}
};
最后,我的节点是如何设置的:
class node
{
public:
T dataItem;
node* linkPointer;
// construct a new node and initialize its attributes with the given parameters.
node(T i, node* l): dataItem(i), linkPointer(l)
{
};
};
node* headPointer;
};
template <class T>
void linklist<T>::insertEnd(T anItem)
{
if(this->headPointer == NULL) //you were assigning null instead of comparing
{
headPointer = new node(anItem, NULL);
}
//rest of the code here
试试这个
这句话中似乎有问题,这里不是比较,而是赋值。
if(this->headPointer = NULL)
使用此:
if(this->headPointer == NULL)
或
if(NULL == this->headPointer) // This is better way to compare.