这个问题的另一个解决方案是,当您将每个列表中的数字相加时,将它们相加以获得等于两个列表之和的大和,将该和转换为字符串,并将字符串的每个字符附加到一个新列表中。希望它可以帮助某人。下面是代码。
节点.h 文件
#ifndef node_h
#define node_h
class LinkedList
{
private:
struct node
{
int data;
node *next;
};
node *head;
public:
LinkedList ();
node *createNode (int key);
void appendNodeBack (const int &key);
void printList ();
int SumOfNodes (const LinkedList list1);
};
#endif
节点.cpp 文件
#include "node.h"
#include <math.h>
LinkedList::LinkedList ():head(NULL) {}
LinkedList::node *LinkedList::createNode (int key)
{
node *newNode = new node;
newNode->data = key;
newNode->next = NULL;
return newNode;
}
void LinkedList::appendNodeBack (const int &key)
{
node *newNode = createNode (key);
//if tree is empty
if (head == NULL)
{
head = newNode;
return;
}
//if tree is not empty
//traverse to the last node in the list
node *temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
void LinkedList::printList ()
{
//if tree is empty
if (head == NULL)
{
std::cout << "Tree is empty!\n";
return;
}
//if tree not empty
node *temp = head;
while (temp != NULL)
{
std::cout << temp->data<<"-->";
temp = temp->next;
}
std::cout << "NULL\n";
}
int LinkedList::SumOfNodes (const LinkedList list1)
{
//find the length of the list
node *temp = head;
int count = 0;
while (temp != NULL)
{
count++;
temp = temp->next;
}
//re-assign temp to head
temp = head;
//calculate the sum
unsigned int sum = 0;
for (unsigned int i = 1; i < pow (10, count); i = i * 10)
{
sum = sum + temp->data * i;
temp = temp->next;
}
return sum;
}
main.cpp 文件
#include <iostream>
#include "node.cpp"
int main ()
{
LinkedList list1, list2, list3;
list1.appendNodeBack (2);
list1.appendNodeBack (3);
list1.appendNodeBack (5);
list1.appendNodeBack (4);
list2.appendNodeBack (5);
list2.appendNodeBack (6);
list2.appendNodeBack (7);
list2.appendNodeBack (8);
list1.printList ();
std::cout << list1.SumOfNodes (list1) << std::endl;
list2.printList ();
std::cout << list2.SumOfNodes (list2) << std::endl;
unsigned int sum = list1.SumOfNodes (list1) + list2.SumOfNodes (list2);
//convert the number to string
std::string str = std::to_string (sum);
//append integer value to the new list
for (unsigned int i = 0; i < str.length (); i++)
list3.appendNodeBack (int (str[i] - '0'));
std::cout << "The new list becomes\n";
list3.printList();
return 0;
}