题目:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:

代码:
- 解法一
/**
* 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) {
ListNode p1=l1;
ListNode p2=l2;
ListNode root=new ListNode(0); //创建新的节点root
ListNode rear=root;
int carry=0; //进位
while(p1!=null||p2!=null||carry!=0){ //只有两个链表都为空并且进位为0时 才结束
ListNode n=new ListNode(0); //创建结点
n.val=((p1==null?0:p1.val)+(p2==null?0:p2.val)+carry)%10; //给结点进行赋值
carry=((p1==null?0:p1.val)+(p2==null?0:p2.val)+carry)/10; //进位进行重赋值
rear.next=n;
rear=n;
p1=(p1==null?p1:p1.next); //后移
p2=(p2==null?p2:p2.next); //后移
}
return root.next;
}
}
- 别人的代码
/**
* 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) {
ListNode firstNode = null, lastNode = null, currentNode = null;
int carry = 0;
while (l1 != null || l2 != null) {
int val1 = 0, val2 = 0;
if (l1 != null) {
val1 = l1.val;
l1 = l1.next;
}
if (l2 != null) {
val2 = l2.val;
l2 = l2.next;
}
int combineVal = val1 + val2 + carry;
if (combineVal > 9) {
carry = 1;
combineVal = combineVal % 10;
} else {
carry = 0;
}
currentNode = new ListNode(combineVal);
if (firstNode == null) {
firstNode = currentNode;
lastNode = currentNode;
} else {
lastNode.next = currentNode;
lastNode = lastNode.next;
}
}
if (carry == 1) {
lastNode.next = new ListNode(1);
}
return firstNode;
}
}
4728



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



