题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/31/linked-list/82/
题目描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:1.当相加有进位 新增加一个节点.2. 用相加数取对10取余获得该位的数字.3.如果没有进位,就直接相加.存入节点.4.如果有链表先遍历完,把剩下的链表加入.
操作起来有点难.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmp = null;
ListNode result = null;//存放结果链表
int carry = 0;
while (l1 != null || l2 != null||carry != 0) { //一定要带上carry !=0
int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
carry = sum / 10;//如果有进位,由于carry=1 进行下一位数运算时加1
ListNode node = new ListNode(sum % 10);
//node存放该位的数字,个位.进位已经保存在Carry中
if (tmp == null) {
tmp = node;
result = tmp;
} else {
tmp.next = node;
tmp = tmp.next;
}
l1 = l1 == null ? null : l1.next;//如果不为空,遍历向下一个节点
l2 = l2 == null ? null : l2.next;
}
return result;
}
}
//解二
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode resultHead = new ListNode(0);
ListNode currentResultNote = resultHead;
int carry = 0;
while(l1!=null||l2!=null) {
int sum = carry+(l1!=null?l1.val:0)+(l2!=null?l2.val:0);
carry=sum/10;
currentResultNote.next = new ListNode(sum%10);
currentResultNote=currentResultNote.next;
if(l1!=null) {
l1=l1.next;
}
if(l2!=null) {
l2=l2.next;
}
}
if(carry>0) {
currentResultNote.next=new ListNode(carry);
}
return resultHead.next;
}
}