You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Analysis:
1. 两个指针一起遍历,若有一个先为null,则在剩余的遍历中加0代替之。
2. 遍历结束之后,若还需进位,则应该再创建一个新的结点用于存储这个carry。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
else if(l2 == null) {
return l1;
}
ListNode c1 = l1;
ListNode c2 = l2;
ListNode res = new ListNode(-1);
ListNode c3 = res;
ListNode tail = null;
int carry = 0;
while(c1 != null || c2 !=null) { // once null, add 0 instead
int v1 = c1==null ? 0 : c1.val;
int v2 = c2==null ? 0 : c2.val;
c3.val = (v1+v2+carry) % 10;
c3.next = new ListNode(-1);
tail = c3;
c3 = c3.next;
carry = (v1+v2+carry) / 10;
c1 = c1==null ? null : c1.next;
c2 = c2==null ? null : c2.next;
}
if(carry == 1) { // one more bit needs
c3.val = carry;
}
else {
tail.next = null; // delete the last redundant bit
}
return res;
}
}
Update 02/04/2014:
iterative:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2 == null) return l1;
ListNode c1 = l1;
ListNode c2 = l2;
ListNode res = new ListNode(-1);
ListNode c3 = res;
int carry = 0;
while(c1 != null || c2 !=null) { // once null, add 0 instead
int v1 = c1==null ? 0 : c1.val;
int v2 = c2==null ? 0 : c2.val;
c3.next = new ListNode((v1+v2+carry) % 10);
c1 = c1==null ? null : c1.next;
c2 = c2==null ? null : c2.next;
carry = (v1+v2+carry) / 10;
c3 = c3.next;
}
if(carry==1) c3.next=new ListNode(carry); // one more bit needs
return res.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2, int carry) {
if(l1==null && l2==null && carry==0) return null;
int val = carry;
if(l1!=null) val+=l1.val;
if(l2!=null) val+=l2.val;
ListNode result = new ListNode(val%10);
result.next = addTwoNumbers(l1==null?null:l1.next,
l2==null?null:l2.next,
val>=10?1:0);
return result;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addTwoNumbers(l1, l2, 0);
}
}

本文介绍了一种通过链表实现两数相加的方法,包括算法解析、迭代和递归两种实现方式,以及如何处理进位情况。
501

被折叠的 条评论
为什么被折叠?



