My problem is asking to have two linked lists where each node has one value and add them together into a different linked list. But, in order to get the digits of the list, I will have to do the modulo and division operator to shift my decimal and get the digits. I am using the power function as an increment of my index through the list and able to add them together. However, in the end is not printing my output. Everything looks fine, but the new linked list is not showing up. This is what I have:
#include <iostream>
#include <math.h>
using namespace std;
class elem {
public:
int data;
elem * next;
elem * prev;
elem()
{
next = prev = NULL;
}
};
elem *head = NULL;
int num(elem * head) { //Putting the head in the last element
int mem = 0;
int powr = 0;
for (elem * p = head; p != NULL; p = p->next) {
mem += p->data * pow(10, powr);
powr++; //Increments the list +1
}
return mem; //Returns the sum
/*
ex. first element is 6, then it will be 6 x 10^0 = 6
second element is 1, then it will become 1 x 10^1 = 10
third element is 7, then it will become 7 x 10^2 = 700
total mem = 700 + 10 + 6 = 716
linked list form (7 -> 1 -> 6)
*/
}
int digit(int value) {
int mem = 0;
while (value > 0) {
value /= 10;
mem++;
}
return value;
}
elem * listSum(elem * listOne, elem * listTwo) {
int temp1 = num(listOne); //List #1
int temp2 = num(listTwo); //List #2
int sum = temp1 + temp2; //New sum
int digits = digit(sum); //New element with the sum of both
elem * list = NULL;
elem * last = NULL;
for (int ii = 0; ii<digits; ii++) {
elem * p = new elem;
p->next = NULL;
if (list == NULL) {
list = p;
}
else {
last->next = p;
}
p->data = sum % 10; //Gets the digit
sum /= 10; //Reduces the decimal
last = p; //Adds the new value into the last (from 7->1->6 it is going to become 617)
}
return list;
}
void main() {
//Make first list
// 7 -> 1 -> 6 -> NULL
elem * a1 = new elem;
a1->data = 7;
elem * b1 = new elem;
b1->data = 1;
elem * c1 = new elem;
c1->data = 6;
a1->next = b1;
b1->next = c1;
c1->next = NULL;
elem * firstHead = a1;
//Make second list
// 5 -> 9 -> 2 -> NULL
elem * a2 = new elem;
a2->data = 5;
elem * b2 = new elem;
b2->data = 9;
elem * c2 = new elem;
c2->data = 2;
a2->next = b2;
b2->next = c2;
c2->next = NULL;
elem * secondHead = a2;
elem * newHead = listSum(firstHead, secondHead);
/*
( 7 -> 1 -> 6) + (5 -> 9 -> 2) would be 617 + 295 = 3rd new node
*/
for (elem * p = newHead; p != NULL; p = p->next) {
cout << p->data;
//Output should be: 2 -> 1 -> 9. Which is 912
}
}
As a test case, I made a print function to see if is printing the list for the sum, but it says that is empty. My other values looks fine when it prints. Any thoughts?