У меня есть функция 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
}
}
}
Но по какой-то причине он не работает :( Какие-нибудь советы?
Заранее спасибо!
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(...){ /* do nothing */ }
так какtemp = temp->link
уже достаточна, вам не нужно ничего делать в петле.