Добавление элемента в конец списка ссылок

0

У меня есть функция 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
        }
    }
}

Но по какой-то причине он не работает :( Какие-нибудь советы?

Заранее спасибо!

Теги:
linked-list

3 ответа

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.

  • 0
    Хорошо, что работает сейчас :). Спасибо! Почему в этом случае должна быть точка с запятой после цикла for?
  • 0
    Точка с запятой в этом случае рассматривается как пустой блок кода, например: for(...){ /* do nothing */ } так как temp = temp->link уже достаточна, вам не нужно ничего делать в петле.
0

Когда список не пуст, 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;  
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
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню