zoukankan      html  css  js  c++  java
  • [LeetCode] 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

    这题虽然归类到Medium 但是难度不大,只是要考虑的东西有点多,比如:两个list不一定一样长,进位这两个问题。

    因为两个数字是逆序存到链表里的,所以这大大简化了问题难度,因为只需要向着链表遍历方向往前进位就可以了。

    void addIter(ListNode *l1, ListNode *l2, ListNode *prev, int carry) {
        if (!l1 && !l2 && carry == 0) return;
        ListNode *node;
        int val = 0;
        if (l1) {
            val += l1->val;
        }
        if (l2) {
            val += l2->val;
        }
        val += carry;
        carry = val / 10;
        val = val % 10;
        
        node = new ListNode(val);
        if (prev) {
            prev->next = node;
        }
        
        addIter(l1 ? l1->next : NULL, l2 ? l2->next : NULL, node, carry);
    }
    
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        ListNode *ret = new ListNode(0);
        addIter(l1, l2, ret, 0);
        return ret->next;
    }
  • 相关阅读:
    第三周课程总结&实验报告
    2019春学习总结
    第十二周
    第十一周
    第十周
    第九周
    第八周作业
    第七周作业
    实验报告3&学习总结
    实验报告2
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4117920.html
Copyright © 2011-2022 走看看