C++ 将元素添加到linkedlist的末尾
我有一个功能headinsert,它可以工作。这在“头部”添加了元素。 但是我试图创建一个函数endinsert,在链表的末尾添加一个元素。 到目前为止,我的代码是:C++ 将元素添加到linkedlist的末尾,c++,linked-list,C++,Linked List,我有一个功能headinsert,它可以工作。这在“头部”添加了元素。 但是我试图创建一个函数endinsert,在链表的末尾添加一个元素。 到目前为止,我的代码是: void IntList::endInsert(int the_number) { if (head == NULL)//if list is empty { head = new IntNode; //create new dynamic variable head -> d
void IntList::endInsert(int the_number)
{
if (head == NULL)//if list is empty
{
head = new IntNode; //create new dynamic variable
head -> data = the_number; //add value to new variable
head -> link = NULL;
}
else
{
NodePtr temp = head; //initialize
//Now we want to insert in the back of list. Use for loop to get to the last element of list
for(temp = head; temp-> link != NULL ; temp = temp -> link)
{
temp->link = new IntNode; //create a new var
temp = temp ->link; //give it a "position"
temp ->data = the_number; //Give it a value
temp ->link = NULL; //The new variable will be the last element and therefore points to NULL
}
}
}
但由于某种原因,它不起作用:(。有什么建议吗
提前谢谢
for(temp = head; temp->link != NULL ; temp = temp->link);
// now temp is the last one
temp->link = new IntNode;
temp = temp->link;
temp->data = the_number;
temp->link = NULL;
请注意
;
for循环末尾的。当列表in不为空时,for()
应循环到最后一个节点,然后创建并附加一个新节点,如下所示
for(temp = head; temp-> link != NULL ; temp = temp -> link) ; // at the end you
are at last node
// Now form a link from last node to newly created one
temp->link = new IntNode;
temp = temp ->link;
temp ->data = the_number;
temp ->link = NULL;
更改代码的这一部分
else
{
NodePtr temp = head; //initialize
//Now we want to insert in the back of list. Use for loop to get to the last element of list
for(temp = head; temp-> link != NULL ; temp = temp -> link)
{
temp->link = new IntNode; //create a new var
temp = temp ->link; //give it a "position"
temp ->data = the_number; //Give it a value
temp ->link = NULL; //The new variable will be the last element and therefore points to NULL
}
}
以下
else
{
NodePtr temp = head; //initialize
//Now we want to insert in the back of list. Use for loop to get to the last element of list
while ( temp-> link != NULL ) temp = temp -> link;
temp->link = new IntNode;
temp->link->link = NULL;
temp->link->data = the_number; //Give it a value
}
好了,现在可以了:)。非常感谢。为什么在本例中for循环后面必须有一个分号?在本例中,分号被视为空代码块,例如:for(…){/*do nothing*/}
因为temp=temp->link
已经足够了,所以不需要在循环中执行任何其他操作。