給定兩個非空鏈表來表明兩個非負整數。數字最高位位於鏈表開始位置。它們的每一個節點只存儲單個數字。將這兩數相加會返回一個新的鏈表。java
你能夠假設除了數字 0 以外,這兩個數字都不會以零開頭。ide
進階:spa
若是輸入鏈表不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。code
示例:rem
輸入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 8 -> 0 -> 7it
/** * 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) { //棧 LinkedList<Integer> s1 = new LinkedList<>(); LinkedList<Integer> s2 = new LinkedList<>(); while(l1 != null) { s1.addFirst(l1.val); l1 = l1.next; } while(l2 != null) { s2.addFirst(l2.val); l2 = l2.next; } int carry = 0; ListNode lastNode = null; while(!s1.isEmpty() || !s2.isEmpty()) { int a1 = 0, a2 = 0; if(!s1.isEmpty()) { a1 = s1.removeFirst(); } if(!s2.isEmpty()) { a2 = s2.removeFirst(); } ListNode curNode = new ListNode((a1 + a2 + carry) % 10); carry = (a1 + a2 + carry) / 10; curNode.next = lastNode; lastNode = curNode; } if(carry > 0) { ListNode curNode = new ListNode(carry); curNode.next = lastNode; lastNode = curNode; } return lastNode; } }
給定兩個非空鏈表來表明兩個非負整數。數字最高位位於鏈表開始位置。它們的每一個節點只存儲單個數字。將這兩數相加會返回一個新的鏈表。io
你能夠假設除了數字 0 以外,這兩個數字都不會以零開頭。ast
進階:class
若是輸入鏈表不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。List
示例:
輸入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 8 -> 0 -> 7
/** * 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) { //棧 LinkedList<Integer> s1 = new LinkedList<>(); LinkedList<Integer> s2 = new LinkedList<>(); while(l1 != null) { s1.addFirst(l1.val); l1 = l1.next; } while(l2 != null) { s2.addFirst(l2.val); l2 = l2.next; } int carry = 0; ListNode lastNode = null; while(!s1.isEmpty() || !s2.isEmpty()) { int a1 = 0, a2 = 0; if(!s1.isEmpty()) { a1 = s1.removeFirst(); } if(!s2.isEmpty()) { a2 = s2.removeFirst(); } ListNode curNode = new ListNode((a1 + a2 + carry) % 10); carry = (a1 + a2 + carry) / 10; curNode.next = lastNode; lastNode = curNode; } if(carry > 0) { ListNode curNode = new ListNode(carry); curNode.next = lastNode; lastNode = curNode; } return lastNode; } }