問題:node
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.git
You may assume the two numbers do not contain any leading zero, except the number 0 itself.input
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.it
Example:io
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
解決:class
① 反轉兩個鏈表,相加以後再反轉回來。List
class Solution { //54ms
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode p1 = reverse(l1);
ListNode p2 = reverse(l2);
int carry = 0;
ListNode header = new ListNode(-1);
ListNode cur = header;
while(p1 != null || p2 != null || carry != 0){
int x = p1 == null ? 0 : p1.val;
int y = p2 == null ? 0 : p2.val;
int sum = x + y + carry;
ListNode tmp = new ListNode(sum % 10);
carry = sum / 10;
tmp.next = cur.next;
cur.next = tmp;
cur = header;
if(p1 != null) p1 = p1.next;
if(p2 != null) p2 = p2.next;
}
return header.next;
}
public static ListNode reverse(ListNode head){
if (head == null || head.next == null) return head;
ListNode header = new ListNode(-1);
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = header.next;
header.next = cur;
cur = next;
}
return header.next;
}
}鏈表
② 不反轉,原地相加。首先計算長度,而後直接將對應的各位相加,最終,再掃描一次鏈表,更新每一個節點的數值,加上進位。next
class Solution {//54ms
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null) return null;
int len1 = 0;
int len2 = 0;
ListNode p1 = l1;
ListNode p2 = l2;
while(p1 != null){//計算鏈表的長度
p1 = p1.next;
len1 ++;
}
while(p2 != null){
p2 = p2.next;
len2 ++;
}
int len = Math.max(len1,len2);
ListNode pre = null;
ListNode head;
head = len1 > len2 ? l1 : l2;
while(len != 0){
int x = 0;
int y = 0;
if(len <= len1){
x = l1.val;
l1 = l1.next;
}
if(len <= len2){
y = l2.val;
l2 = l2.next;
}
len --;
head.val = x + y;
head.next = pre;
pre = head;
head = len1 > len2 ? l1 : l2;
}
head = pre;
pre = null;
int carry = 0;
while(head != null){
int cur = head.val + carry;
head.val = cur % 10;
carry = cur / 10;
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
if(carry != 0){
ListNode result = new ListNode(carry);
result.next = pre;
return result;
}
return pre;
}
}static