2014-02-03 3 views
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 
     } 
    } 
} 

Но по какой-то причине он не работает :(Любые советы

Спасибо заранее

ответ

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? – user3265963

+0

Точка с запятой в этом случае рассматривается как пустой блок кода, например: 'for (...) {/ * do nothing * /}', потому что уже существует 'temp = temp-> link', вы не нужно сделать что-нибудь еще в цикле. – fede1024

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; 
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 
} 
Смежные вопросы