原文:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
译文:
你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
例子:(3 -> 1 -> 5), (5 -> 9 -> 2)
输入:8 -> 0 -> 8
package chapter_2_LinkedLists;
import java.util.Scanner;
/**
*
你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的, 也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
例子:(3 -> 1 -> 5), (5 -> 9 -> 2)
输入:8 -> 0 -> 8
*
*/
public class Question_2_4_2 {
/**
* 同时扫描两个数字序列,并计算结果保存进位,结果sum存储在sum链表中
*/
public static void calculateSum(LinkList_4 linkListA, LinkList_4 linkListB, LinkList_4 sumList) {
Node_4 listA = linkListA.head, listB = linkListB.head;
Node_4 cur = sumList.head;
int curSum, a = 0, b = 0;
int add = 0;
while (listA != null || listB != null) {
Node_4 node = new Node_4();
a = listA != null ? listA.data : 0;
b = listB != null ? listB.data : 0;
curSum = a + b + add;
if (curSum > 9) {
curSum %= 10;
add = 1;
} else {
add = 0;
}
node.data = curSum;
if (cur == null) {
sumList.head = node;
cur = node;
} else {
cur.next = node;
cur = node;
}
if(listA != null) {
listA = listA.next;
}
if(listB != null) {
listB = listB.next;
}
}
// 最高位如果存在进位运算
if (add > 0) {
Node_4 node = new Node_4();
node.data = add;
if (cur == null) {
sumList.head = node;
cur = node;
} else {
cur.next = node;
cur = node;
}
}
}
/**
* 输出结果链表
*/
public static void printSum(LinkList_4 sumList) {
Node_4 cur = sumList.head;
if(sumList.head == null) {
System.out.format("空\n");
return;
}
while (cur != null) {
System.out.format("%3d", cur.data);
cur = cur.next;
}
System.out.format("\n");
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
while (num-- > 0) {
int m, n;
LinkList_4 linkListA = new LinkList_4();
LinkList_4 linkListB = new LinkList_4();
LinkList_4 sum = new LinkList_4();
m = scanner.nextInt();
n = scanner.nextInt();
scanner.nextLine();
Node_4 cur = null;
// 输入数字序列A
for (int i = 0; i < m; i++) {
Node_4 node = new Node_4();
int data = scanner.nextInt();
node.data = data;
if (linkListA.head == null) {
linkListA.head = node;
cur = node;
} else {
cur.next = node;
cur = node;
}
}
cur = null;
// 输入数字序列B
for (int j = 0; j < n; j++) {
Node_4 node = new Node_4();
int data = scanner.nextInt();
node.data = data;
if (linkListB.head == null) {
linkListB.head = node;
cur = node;
} else {
cur.next = node;
cur = node;
}
}
// 计算两个序列的和保存在sum序列中
calculateSum(linkListA, linkListB, sum);
printSum(sum);
}
}
}