Для начала переменная head
имеет неопределенное значение и не изменяется в функции.
Node *a;
Node *head = a;
Изменение переменной a
не означает изменение значения выражения a->next
.
// ...
a = new Node((ans%10)+bor);
//...
a=a->next;
Функция может быть записана следующим образом (без тестирования)
Node * addTwoLists( const Node *first, const Node *second )
{
const int Base = 10;
Node *head = nullptr;
int bor = 0;
Node **current = &head;
for ( ; first != nullptr && second != nullptr; first = first->next, second = second->next )
{
int sum = first->data + second->data + bor;
*current = new Node( sum % Base );
bor = sum / Base;
current = &( *current )->next;
}
if ( bor )
{
*current = new Node( bor );
}
return head;
}
Вот демонстрационная программа
#include <iostream>
struct Node
{
explicit Node( int data, Node *next = nullptr ) : data( data ), next( next )
{
}
int data;
Node *next;
};
void push_front( Node **head, int x )
{
*head = new Node( x, *head );
}
Node * addTwoLists( const Node *first, const Node *second )
{
const int Base = 10;
Node *head = nullptr;
int bor = 0;
Node **current = &head;
for ( ; first != nullptr && second != nullptr; first = first->next, second = second->next )
{
int sum = first->data + second->data + bor;
*current = new Node( sum % Base );
bor = sum / Base;
current = &( *current )->next;
}
if ( bor )
{
*current = new Node( bor );
}
return head;
}
std::ostream & display_list( const Node *head, std::ostream &os = std::cout )
{
for ( ; head != nullptr; head = head->next )
{
os << head->data << ' ';
}
return os;
}
int main()
{
const int N = 10;
Node *list1 = nullptr;
Node *list2 = nullptr;
for ( int i = 1; i < N; i++ ) push_front( &list1, i );
for ( int i = N; --i != 0; ) push_front( &list2, i );
display_list( list1 ) << '\n';
display_list( list2 ) << '\n';
Node *list3 = addTwoLists( list1, list2 );
display_list( list3 ) << '\n';
}
Ее вывод
9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9
0 1 1 1 1 1 1 1 1 1