0

我的问题是要求有两个链表,其中每个节点都有一个值,并将它们一起添加到不同的链表中。但是,为了获得列表的数字,我将不得不使用模和除法运算符来移动我的小数并获得数字。我使用幂函数作为列表中索引的增量,并且能够将它们加在一起。但是,最终没有打印我的输出。一切看起来都很好,但是新的链接列表没有出现。这就是我所拥有的:

#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
    }

}

作为一个测试用例,我创建了一个打印函数来查看是否正在打印总和列表,但它说那是空的。我的其他值在打印时看起来不错。有什么想法吗?

4

0 回答 0