• 【leetcode】Add Two Numbers(middle) ☆


    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

    思路:

    看起来像是一道很简单的题,但是我却通过这道题发现了自己对指针掌握的不足。因为要返回一个链表,在链表的循环创建中指针是不断向下指的(ans),所以肯定要保留一个头结点(anshead)。就是在链表和链表头结点上,我纠结了很久。

    首先,定义  anshead = new ListNode(0);  

                    ans = anshead;

    必须先给anshead分配内存,再把ans指向anshead分配的空间中,每次也必须先给 ans->next = new ListNode(0) 赋值后才能写 ans = ans->next;

    总之,必须把ans 指向一个开辟过的空间。

    否则, pre->next 在未开辟时指向 0x00000000 若这时 ans = pre->next 那么ans也是0x00000000 若这时给 ans 分配了空间,pre->next 还是0x00000000 因为之前ans没有明确的指定一个地方。

    题目中只要注意进位就可以了。

    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            if(l1 == NULL) return l2;
            if(l2 == NULL) return l1;
    
            ListNode * anshead = new ListNode(0);
            ListNode * ans = anshead;
            int cur = 0; //当前位的个位数
            int up = 0; //进位
    
            while(ans != NULL) //当没有下一位可以产生时就结束循环
            {
                cur = up;
                if(l1 != NULL)
                {
                    cur += l1->val;
                    l1  = l1->next;
                }
                if(l2 != NULL)
                {
                    cur += l2->val;
                    l2  = l2->next;
                }
                up = cur / 10;
                cur = cur % 10;
                ans->val = cur;
                if(!(up == 0 && l1 == NULL && l2 == NULL)) //有进位 或 l1 l2 不空时才会有下一位
                {
                    ans->next = new ListNode(0);
                }
                ans = ans->next;    
            }
    
            return anshead;
        }
    
        void createList(ListNode * &L)
        {
            int n;
            cin >> n;
            if(n != -1)
            {
                L = new ListNode(n);
                createList(L->next);
            }
        }
    };

    看下大神同样思路,精简版的代码。

    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode preHead(0), *p = &preHead;
        int extra = 0;
        while (l1 || l2 || extra) {
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
            extra = sum / 10;
            p->next = new ListNode(sum % 10);
            p = p->next;
            l1 = l1 ? l1->next : l1;
            l2 = l2 ? l2->next : l2;
        }
        return preHead.next; //不要第一个自己随意赋的值,好方法
    }
    };
  • 相关阅读:
    Leetcode第七题——数的反转
    Leetcode第六题——横向遍历ZIGZAG数组
    26 将查询结果插入到一张表中?
    25 表的复制
    24 insert 语句插入数据
    23 创建表
    22 limit(重点中的重点,以后分页查询全靠它了。)
    21 union(可以将查询结果集相加
    20 子查询
    19 连接查询
  • 原文地址:https://www.cnblogs.com/dplearning/p/4231052.html
Copyright © 2020-2023  润新知