题目:给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
class ListNode{
int val = 0;
ListNode next;
ListNode(int x){
this.val = x;
}
}
//初始链表逆序存储时,将结果也逆序存储
public Solution{
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode headNode = new ListNode(0);
ListNode p = l1 ,q = l2 ,head = headNode;
int carry = 0;
while((p!=null)||(q!=null)){
int val1 = (p!=null)? p.val:0;
int val2 = (q!=null)? q.val:0;
int sum = carry +val1+val2;
carry = sum/10; //进位
head.next = new ListNode(sum%10);
head = head.next;
if(p!=null) p = p.next;
if(q!=null) q = q.next;
}
//当最后一位产生进位时,需要再增加一个结点来存储
if(carry>0){
head.next = new ListNode(carry);
}
return headNode.next;
}
}
拓展
如果链表中的数字不是按逆序存储的呢?例如:
(3→4→2)+(4→6→5)=8→0→7
//正序存储,结果也进行正序存储(头插法)
import java.util.Stack;
public Solution{
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode headNode = new ListNode(0);
ListNode p = l1 ,q = l2 ,head = headNode;
int carry = 0;
Stack<Integer> s1 = new Stack();
Stack<Integer> s2 = new Stack();
while (p != null || q != null) {
if (p!=null) {
s1.push(p.val);
p = p.next;
}
if (q!=null) {
s2.push(q.val);
q = q.next;
}
}
while (!s1.empty()||!s2.empty()) {
int x = (!s1.empty()) ? s1.pop() : 0;
int y = (!s2.empty()) ? s2.pop() : 0;
int sum = carry + x + y;
carry = sum / 10;
//顺序插入
ListNode node = new ListNode(sum % 10);
node.next = head.next;
head.next = node;
}
//当最后一位产生进位时,需要再增加一个结点来存储
if(carry>0){
//头插法,将结果按高位到低位进行顺序存储。
ListNode node = new ListNode(carry);
node.next = head.next;
head.next = node;
}
return headNode.next;
}
}
本地测试代码:
import java.util.Stack;
class ListNode{
int val = 0;
ListNode next;
ListNode(int x){
this.val = x;
}
public class Solution {
ListNode l = new ListNode(0);
ListNode m = new ListNode(0);
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//TODO写入以上代码
}
public void addNode(ListNode l, int data){
ListNode ln = new ListNode(data);
ln.next = l.next;
l.next = ln;
}
public static void main(String[] args){
TwoLinkSum tls = new TwoLinkSum();
ListNode node;
tls.addNode(tls.l,3);
tls.addNode(tls.l,2);
tls.addNode(tls.l,1);
tls.addNode(tls.m,7);
tls.addNode(tls.m,0);
tls.addNode(tls.m,9);
node = tls.addTwoNumbers(tls.l.next,tls.m.next);
while(node!=null){
System.out.println(node.val);
node = node.next;
}
}
}
正序存储时输出的结果:
1
0
3
0
Process finished with exit code 0