65,187
社区成员




struct Node
{
T data;
Node<T>* next;
};
template<class T>
class myList
{
private:
Node<T>* head;
int num;
public:
myList(){head = NULL; num = 0;}
~myList(){}
void insertNode(T elem)
{
num++;
Node<T>* p = head;
Node<T>* temp = new Node<T>;
temp->data = elem;
temp->next = NULL;
if(head == NULL)
{
head = temp; //此处若为 p = temp 则head一直为NULL
cout<<"one node inserted\n";
}
else
{
while(p->next != NULL) // p==NULL
{
cout<<"inserting...\n";
p = p->next;
}
p->next = temp; //p=temp;
}
}
};
while(p->next != NULL) // p==NULL
{
cout<<"inserting...\n";
p = p->next;
}
然后插入temp
p->next = temp; //p=temp;
这样如你所说是没有问题的。但是如果你改成注释的代码。就是到了最后一个元素的后面也就是NULL,NULL怎么会有next呢,再说了如果你执行p=temp这句并没有把temp和链表连在一起。只是让p指向了temp而已。