我的问题是要求有两个链接列表,其中每个节点都有一个值,并将它们一起添加到不同的链表中。但是,为了得到列表的数字,我将不得不做模数和除法运算符来移动我的小数并得到数字。我通过列表使用power函数作为索引的增量,并能够将它们一起添加。但是,到底是不是打印我的输出。一切看起来都很好,但新的链表没有显示出来。这就是我所拥有的:
#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
}
}
作为一个测试案例,我创建了一个打印函数来查看是否打印了总和的列表,但它说是空的。打印时我的其他值看起来很好。有什么想法吗?