題目
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
作答
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int up = 0 ,sum = 0 ;
ListNode node=null, start=null;
do{
if(l1!=null&&l2!=null){
sum = l1.val + l2.val+up;
up = 0;
if(sum>=10){
up = 1;
sum = sum % 10 ;
}
if(node==null){
node = new ListNode(sum);
start = node ;
}else{
node.next = new ListNode(sum);
node = node.next;
}
}
l1 = l1 !=null? l1.next:null;
l2 = l2 !=null? l2.next:null;
//判斷位數(shù)不一樣的情況
if(l1==null&&l2!=null){
sum = l2.val+up;
up = 0;
if(sum>=10){
up = 1;
sum = sum % 10 ;
}
node.next = new ListNode(sum);
node = node.next;
}
if(l2==null&&l1!=null){
sum = l1.val+up;
up = 0;
if(sum>=10){
up = 1;
sum = sum % 10 ;
}
node.next = new ListNode(sum);
node = node.next;
}
}while(l1!=null||l2!=null);
//處理為完成的部分
if(up==1){
node.next = new ListNode(1);
}
return start;
}
}