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

Subscribe to see which companies asked this question

C++

    Adne:原题的大概意思是:你被给予2个链接的列表,代表2个非负数。该数字以反向顺序存储,每个节点包含一个数字。把这两个数字加起来,把它作为一个链表。 当然要考虑两个数字加起来大于10这种情况了,而且还有可能是两个链表的 长度可能会不相等。所以一种解决方法是,每次都判断两个链表是否为空,如果一个链表较短直接为空了,则将其赋值为0,然后再相加,这样就省去了处理剩余链表的麻烦.。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution{
    public:
	ListNode* addTwoNumbers(ListNode* l1,ListNode* l2){
		 ListNode *head = NULL, *prev = NULL ;
		 int carry = 0;
		 while(l1 || l2){
		 	int v1 = l1 ? l1-> val : 0;
		 	int v2 = l2 ? l2-> val : 0;
		 	int tmp = v1 + v2 + carry ;
		 	carry = tmp /10 ;
		 	int val = tmp % 10;
		 	ListNode* cur = new ListNode(val);
		 	if(!head) head = cur;
		 	if(prev) prev->next = cur;
		 	prev = cur;
		 	l1 = l1?l1->next:NULL;
		 	l2 = l2?l2->next:NULL;  
		 }
		 if(carry > 0){
		 	ListNode* l = new ListNode(carry);
		 	prev ->next = l;
		 }
		 return head;
	}
};
Aden:来个递归的短版本,对于递归我总有那么点理解不了,感觉就是堵得慌,还是智商有限、、
class Solution {

    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            if (l1 == NULL and l2 == NULL) return NULL;
            else if (l1 == NULL) return l2; 
            else if (l2 == NULL) return l1; 

            int a = l1->val + l2->val;
            ListNode *p = new ListNode(a % 10);
            p->next = addTwoNumbers(l1->next,l2->next);
            if (a >= 10) p->next = addTwoNumbers(p->next, new ListNode(1));
            return p;
        }
  };

Aden:在来个java版本的吧,最近也在学java。。我也不明白,为什么同样思路的代码,java比C/C++都要快好多...

/**
 * 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 fake = new ListNode(0);
    ListNode t=fake, t1=l1, t2=l2;
    int a1, a2, r = 0;
    while (t1!=null || t2!=null || r!=0) {
        a1 = t1==null ? 0:t1.val;
        a2 = t2==null ? 0:t2.val;
        r += a1 + a2;
        t.next = new ListNode(r%10);
        r /= 10;
        t = t.next;
        if (t1!=null) t1 = t1.next;
        if (t2!=null) t2 = t2.next;
    }
    return fake.next;
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值