两数相加( Add Two Numbers)
题目描述
中文描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
English
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807
难度:中等
解题思路
两个数相加时,直接从链表的头开始对齐相加,结果保存在一个新的链表中,最后再遍历结果链表,将值大于10的节点进行进位
代码实现
public class ListNode {
int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1=l1;
ListNode head2=l2;
ListNode result=null;
ListNode reHead=result;
if (head1!=null && head2!=null){
result=new ListNode(head1.val+head2.val);
head1=head1.next;
head2=head2.next;
reHead=result;
}
while (head1!=null && head2!=null){
reHead.next=new ListNode(head1.val+head2.val);
head1=head1.next;
head2=head2.next;
reHead=reHead.next;
}
while (head1!=null){
reHead.next=new ListNode(head1.val);
head1=head1.next;
reHead=reHead.next;
}
while (head2!=null){
reHead.next=new ListNode(head2.val);
head2=head2.next;
reHead=reHead.next;
}
reHead=result;
while (reHead!=null){
if (reHead.val>=10){
if (reHead.next!=null){
reHead.next.val+=reHead.val/10;
}else {
reHead.next=new ListNode(reHead.val/10);
}
reHead.val=reHead.val%10;
}
reHead=reHead.next;
}
return result;
}
}