原题:
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.
示例:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目的意思是用链表的方式实现两个非负整数的相加。每一位都是一个节点,且个位在最前面。简单点来说就是我们小学刚学数字加法的时候的进位。【大数的加法运算】
我最初的思路,一种递归的思想不停地计算下个节点的下个节点。。。
public class Solution2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int x = l1.val + l2.val;
int i = 0;
if (x >= 10) {
x = x % 10;
i = 1;
}
ListNode listNode = new ListNode(x);
if (l1.next != null || l2.next != null || i != 0)
listNode.next = addTwoNumbersx(l1.next, l2.next, i);
return listNode;
}
private ListNode addTwoNumbersx(ListNode l1, ListNode l2, int j) {
int x;
int i = 0;
ListNode listNode;
int k1, k2;
ListNode next1;
ListNode next2;
if (l1 == null) {
k1 = 0;
next1 = null;
} else {
k1 = l1.val;
next1 = l1.next;
}
if (l2 == null) {
k2 = 0;
next2 = null;
} else {
k2 = l2.val;
next2 = l2.next;
}
x = k1 + k2 + j;
if (x >= 10) {
x = x % 10;
i = 1;
}
listNode = new ListNode(x);
if (next1 != null || next2 != null || i != 0)
listNode.next = addTwoNumbersx(next1, next2, i);
return listNode;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
虽然Accepted了,但是效率并不高。后来看了另外一篇博客http://blog.csdn.net/DERRANTCM/article/details/46905467,觉得他的做法更加高效。
import java.util.List;
public class Solution2_2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1;
ListNode p2 = l2;
ListNode root = new ListNode(0);
ListNode r = root;
int carry = 0;
int s;
while (p1 != null && p2 != null) {
s = p1.val + p2.val + carry;
carry = s / 10;
p1.val = s % 10;
r.next = p1;
r = p1;
p1 = p1.next;
p2 = p2.next;
}
if (p1 != null) {
r.next = p1;
} else if (p2 != null) {
r.next = p2;
}
if (carry == 1) {
while (r.next != null) {
s = r.next.val + carry;
r.next.val = s % 10;
carry = s / 10;
r = r.next;
}
if (carry > 0) {
r.next = new ListNode(1);
}
}
return root.next;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
持续学习中ing。。。。