兩數相加( 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;
}
}