题目:http://oj.leetcode.com/problems/add-two-numbers/
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
题目翻译:
给定两个链表表示两个非负数。数字逆序存储,每个节点包含一个单一的数字。计算两个数的和,并以链表的形式返还。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode res = null;
int a = 0;
while (l1!=null || l2!=null) {
int sum = a;
if (l1!=null) {
sum += l1.val;
l1 = l1.next;
}
if (l2!=null) {
sum += l2.val;
l2 = l2.next;
}
if (sum/10 > 0) {
a = 1;
} else {
a = 0;
}
sum = sum%10;
ListNode tmp = new ListNode(sum);
if (res == null) {
head = tmp;
} else {
res.next = tmp;
}
res = tmp;
}
if (a == 1) {
ListNode tmp = new ListNode(1);
res.next = tmp;
}
return head;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
var head, res, a = 0;
while (l1 || l2) {
var sum = a;
if (l1) {
sum += l1.val
l1 = l1.next;
}
if (l2) {
sum += l2.val
l2 = l2.next;
}
if (sum >= 10) {
a = 1;
} else {
a = 0;
}
sum = sum % 10;
var tmp = new ListNode(sum);
if (res === undefined) {
head = tmp;
} else {
res.next = tmp;
}
res = tmp;
}
if (a === 1) {
tmp = new ListNode(a);
res.next = tmp;
}
return head;
};
本文详细解释了如何解决LeetCode中的链表加法问题,即给定两个链表表示的非负整数,实现两数相加并返回结果链表。通过迭代遍历链表,处理进位,最终得到正确的答案。重点在于理解链表操作和进位处理。
502

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



