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.
Your input {1,2,8} {1,8,1}
Your answer{2,0,0,1}
一道鏈表題 需要注意點的有三個
第一: 正常的進位問題(包括上一步運算的進位1 加上這次運算的結(jié)果又有進位)
第二: 如果兩個鏈表不一樣長悔常,如何不在判斷和向下傳輸?shù)倪^程不返回空指針異常
第三: 最后一位運算時如果有進位怎么辦;
/**
* 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 resultList = new ListNode(0);
? ? ? ? ListNode temp = resultList;
? ? ? ? ListNode mSum = new ListNode(0);
? ? ? ? while(l1 != null || l2 != null){
? ? ? ? ? ? int list1 = (l1 != null) ? l1.val : 0;
? ? ? ? ? ? int list2 = (l2 != null) ? l2.val : 0;
? ? ? ? ? ? int sum = list1 + list2;
? ? ? ? ? ? int dSum = (sum + mSum.val) % 10;
? ? ? ? ? ? //int input = (dSum + mSum.val) % 10;
? ? ? ? ? ? temp = temp.next = new ListNode(dSum);
? ? ? ? ? ? mSum = mSum.next = new ListNode((sum + mSum.val) / 10);
? ? ? ? ? ? l1 = (l1 == null) ? null : l1.next;
? ? ? ? ? ? l2 = (l2 == null) ? null : l2.next;
? ? ? ? }
? ? ? ? if(mSum.val == 1){
? ? ? ? ? ? temp.next = new ListNode(1);
? ? ? ? }
? ? ? ? return resultList.next;
? ? }
}