I want to create two linked lists by taking user input, and then add them and store the sum in a third linked list. However, when I print the third linked list, it always prints 0 as the first value, followed by the correct sum values. Tried to debug and step through the AddTwoLists() function, but couldn't figure out where that 0 came from. I haven't included cases where the length of the two lists are different. Just trying to fix this problem first.
#include <iostream>
struct Node {
int n; // number of non-zero values
int index;
int value;
Node* link;
};
struct Data {
int n;
int index;
int value;
};
Node* A;
Node* B;
void AddEndNode(Node*& head, int index, int value){
Node* current = head;
Node* temp = new Node;
// temp->n = n;
temp->index = index;
temp->value = value;
temp->link = NULL;
if(current == NULL) head = temp;
else{
while(current->link != NULL) current = current->link;
current->link = temp;
}
}
void PrintList(Node* head){
Node* current = head;
while(current != NULL){
std::cout<< current->value<< "\t";
current = current->link;
}
std::cout<< "\n";
}
void AddTwoLists(Node* A, Node* B){
Node* currentA = A;
Node* currentB = B;
Node* C = new Node;
C->n = A->n;
C->link = NULL;
int sum = 0;
int index = 1;
while(currentA != NULL){
sum = 0;
C->index = index;
sum += currentA->value;
std::cout<< "\n1st sum is "<< sum;
sum += currentB->value;
std::cout<< "\n2nd sum is "<< sum;
AddEndNode(C, index, sum);
std::cout<< "\nlist C is ";
PrintList(C);
currentA = currentA->link;
currentB = currentB->link;
index++;
}
PrintList(C);
}
int main() {
Data dataA, dataB;
dataA.index = 1;
dataB.index = 1;
A = NULL;
B = NULL;
std::cout<< "How many non-zero whole numbers do you want to add to list A? \n";
std::cin>> dataA.n;
for(int i =0; i < dataA.n; i++){
std::cout<< "Please enter a non-zero whole number: ";
std::cin>> dataA.value;
AddEndNode(A, dataA.index, dataA.value);
dataA.index++;
}
PrintList(A);
std::cout<< "\nHow many non-zero whole numbers do you want to add to list B? \n";
std::cin>> dataB.n;
for(int i =0; i < dataB.n; i++){
std::cout<< "Please enter a non-zero whole number: ";
std::cin>> dataB.value;
AddEndNode(B, dataB.index, dataB.value);
dataB.index++;
}
PrintList(B);
std::cout<< "\nThe sum of listA and listB: \n";
AddTwoLists(A, B);
return 0;
}