将元素添加到链接列表的末尾

时间:2014-02-03 14:29:46

标签: 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 -> 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
        }
    }
}

但由于某种原因,它不起作用:(。有任何提示吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

当列表非空时,在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;  

答案 2 :(得分:0)

更改代码的这一部分

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
}