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#生成静态两方法
    ASP.NET C# 生成静态页面简单方法
    sql日期格式化
    Div+Css+JS做多个显示/隐藏内容块
    Request获取url各种信息的方法
    asp.net遍历页面所有的按钮(或控件)
    Donews.com:SpyMac.com也提供了1G的Email.
    再见 Swagger UI!国人开源了一款超好用的 API 文档生成框架,Star 4.7K+,真香!!
    面试官:new Object[5] 一共创建了几个对象?
    面试官:select......for update 会锁表还是锁行?别答错了!
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5090387.html
Copyright © 2011-2022 走看看