題目:
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
創建一個頭結點,這個節點不記錄數據,這樣的好處是,不用設計前驅節點,記錄前面節點,返回值時直接返回頭結點的next節點。
/**
* 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 l_final = new ListNode(0);
ListNode l_head = l_final;
ListNode l_iter = new ListNode(0);
int last_tail = 0;
while(l1!=null || l2!=null || last_tail!=0){
if(l1==null)l1 = new ListNode(0);
if(l2==null)l2 = new ListNode(0);
int val = l1.val + l2.val + last_tail;
int tail = val / 10;
int head = val % 10;
l_iter = new ListNode(head);
l_head.next = l_iter;
l_head = l_iter;
last_tail = tail;
l1 = l1.next;
l2 = l2.next;
}
return l_final.next;
}
}