【JAVA、C++】LeetCode 002 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

解题思路:

定义三个ListNode l1、l2,result,其中result为return语句的输出,l1、l2为传入的参数。

将l1赋值给result,执行result.val+=l2.val,然后l1作为指针一级一级往下走,直到走到l2.next为null。当然,之间会有不少边界条件,自己debug一下就好。

Java代码如下:

public class Solution {
static public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result=l1;
while(true){
l1.val+=l2.val;
if(l1.val>=10){
l1.val%=10;
if(l1.next==null) l1.next=new ListNode(1);
else l1.next.val+=1;
} if(l2.next==null){
ListNode l3=l1.next;
while(true){
if (l3==null) break;
if(l3.val==10){
l3.val%=10;
if(l3.next==null) l3.next=new ListNode(1);
else l3.next.val+=1;
}
l3=l3.next;
}
break;
} l2=l2.next;
if(l1.next==null){
l1.next=new ListNode(0);
}
l1=l1.next;
}
return result; }
}

C++

 class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res=l1;
while (true) {
l1->val += l2->val;
if (l1->val >= ) {
l1->val %= ;
if (l1->next == NULL)
l1->next = new ListNode();
else l1->next->val += ;
} if (l2->next == NULL) {
ListNode* l3 = l1->next;
while (true) {
if (l3 == NULL) break;
if (l3->val == ) {
l3->val %= ;
if (l3->next == NULL) l3->next = new ListNode();
else l3->next->val += ;
}
l3 = l3->next;
}
break;
} l2 = l2->next;
if (l1->next == NULL) {
l1->next = new ListNode();
}
l1 = l1->next;
}
return res;
}
};
上一篇:【JAVA、C++】LeetCode 015 3Sum


下一篇:机器学习的5种语言(选自info world)