題目
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
你有兩個(gè)用鏈表代表的整數(shù),其中每個(gè)節(jié)點(diǎn)包含一個(gè)數(shù)字。數(shù)字存儲(chǔ)按照在原來整數(shù)中相反的順序,使得第一個(gè)數(shù)字位于鏈表的開頭。寫出一個(gè)函數(shù)將兩個(gè)整數(shù)相加,用鏈表形式返回和。
樣例
給出兩個(gè)鏈表3->1->5->null 和 5->9->2->null,返回8->0->8->null
分析
這道題類似之前的二進(jìn)制求和,只不過換到了鏈表這種數(shù)據(jù)結(jié)構(gòu)之上,同時(shí)二進(jìn)制變成了十進(jìn)制,要考慮好進(jìn)位的計(jì)算。
代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists(ListNode l1, ListNode l2) {
// write your code here
// write your code here
// save the pre node
ListNode pre = new ListNode(0);
// save the now node
ListNode now = new ListNode(0);
// create a null node to store the result
ListNode result = null;
int val = 0; //
int add = 0; //jinwei
while( l1 != null || l2 != null )
{
val = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + add) % 10;
add = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + add) / 10;
l1 = (l1 == null ? null : l1.next);
l2 = (l2 == null ? null : l2.next);
now.val = val;
if(result == null)
{
result = now;
}
pre = now;
now = new ListNode(0);
pre.next = now;
}
//最后還要多來一次判斷,因?yàn)橛幸环N可能,兩個(gè)鏈表一樣長,最后一位又向上進(jìn)了一位
val = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + add) % 10;
add = ((l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + add) / 10;
now.val = val;
//如果最后一位又向上進(jìn)了一位,新的最后一位不為0,應(yīng)該保留,否則就為0,應(yīng)當(dāng)舍棄
if(now.val == 0){
pre.next = null;
}
return result;
}
}