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

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /*
     * 1.设置进位为0,并判断列表是否为空
     * 2.两个列表都不为空时,遍历,判断两个列表对应的值相加后是否大于10,大于就设置进位为1,否则为0
     * 3.一个列表为空的时候,进位+列表的对应的值,然后将剩下的添加到结果列表的尾部.
    * 4.两个列表都为空,进位位1,也添加
    */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (NULL == l1 && NULL == l2) { return NULL; } else if (NULL == l1) { return l2; } else if (NULL == l2) { return l1; } ListNode* p1 = l1; ListNode* p2 = l2; ListNode* res_head = NULL; ListNode* res_index = NULL; int flag = 0; while (p1 != NULL && p2 != NULL) { int sum = p1->val + p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); if (NULL == res_head) { res_head = res_node; res_index = res_head; } else { res_index->next = res_node; res_index = res_node; } p1 = p1->next; p2 = p2->next; } while (p1 != NULL) { int sum = p1->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p1 = p1->next; } while (p2 != NULL) { int sum = p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p2 = p2->next; } if (0 != flag) { ListNode* res_node = new ListNode(flag); res_index->next = res_node; res_index = res_node; } return res_head; } };
  • 相关阅读:
    刚才遇到了关于C#使用外部DLL函数上的char*的问题。
    重新整理过的 《C#编码规范》
    晕,完全晕了。
    Microsoft Visual Studio 2010 支持html5和css3的补丁包
    [mysql] 修改root密码和查看连接数
    Visual Studio统计有效代码行数
    [c#] 邮件附件为中文名的bug
    游戏名词解释
    [SVN] 以下后缀文件不应该提交入库
    [c#] 语言新特性
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5090387.html
Copyright © 2011-2022 走看看