[leetcode] 学习记录——Add Two Numbers

/**
 * 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) {
    }
};

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.

numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8


分析:这是一道常规的链表操作题目,就是将342 + 465 = 807 的结果存于链表中。但是在做题过程中一开始 想的过于简单,只是想先将他们转化为数字再相加得到结果,存成链表。但是测试用例中有许多的大数,结果int超出表示范围。其实这个链表相加就是解决大数问题的,因为它已经逐位对其了,才用进位思想,代码可以写的非常巧妙。


/**
 * 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) {
      int c,n1,n2;
      c = 0;
      ListNode result(0);
      ListNode *p  = &result;
      while(l1||l2||c){
		    n1= l1==NULL?0:l1->val;
			n2 = l2==NULL?0:l2->val;
			ListNode *t = new ListNode((c+n1+n2)%10);
			p ->next = t;
			p = p->next;
            c = (c+n1+n2)/10;
            l1 = l1==NULL?l1:l1->next;
            l2 = l2==NULL?l2:l2->next;
        }
        return result.next;
    }
};


收获:

【1】 c++构造函数可以这样写

ListNode(int x) : val(x), next(NULL){}

表示给val 初始化为x,next指针初始化为NULL;

那么一开始声明变量时可以这样写 : ListNode result(0);


【2】遗忘的知识点:局部变量在函数返回的时候就会被释放掉,因此要new一个指针变量,来构造链表,这样return的时候链表是完整的。

【3】头指针技巧,由于循环的时候如果没有头指针,还要对第一个指针做特殊的判断和处理,但是有了头指针,就可以一概而论,并且return result.next即可(result声明为头指针)

【4】进位计算技巧,当前位 (c+n1+n2) /10 进位 c =   (c+n1+n2)  % 10 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值