• 两数相加


    给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

    如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

    您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

    示例:

    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807

    好久没用过指针链表了,熟悉一下


     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10     struct ListNode *root = new ListNode(NULL);
    11     struct ListNode *go = root;
    12 public:
    13     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    14         int flag = 0;
    15         while(l1!=NULL && l2!=NULL){
    16             int ans = l1->val + l2->val + flag;
    17             flag = ans/10;
    18             ans = ans%10;
    19             l1 = l1->next;
    20             l2 = l2->next;
    21             struct ListNode* node = new ListNode(ans);
    22             go->next = node;
    23             go = node;
    24         }
    25         while(l1!=NULL){
    26             int ans = l1->val + flag;
    27             flag = ans/10;
    28             ans = ans%10;
    29             l1 = l1->next;
    30             struct ListNode* node = new ListNode(ans);
    31             go->next = node;
    32             go = node;
    33         }
    34         while(l2!=NULL){
    35             int ans = l2->val + flag;
    36             flag = ans/10;
    37             ans = ans%10;
    38             l2 = l2->next;
    39             struct ListNode* node = new ListNode(ans);
    40             go->next = node;
    41             go = node;
    42         }
    43         if(flag){
    44             struct ListNode* node = new ListNode(flag);
    45             go->next = node;
    46         }
    47         return root->next;
    48     }
    49 };
  • 相关阅读:
    spring boot拦截器中获取request post请求中的参数
    netty与spring学习
    拦截器,过滤器,监听器
    CA 根证书不在“受信任的根证书颁发机构”存储区
    SpringBoot整合Shiro
    远程服务接口聚合带来的性能提升
    常见软件安全性漏洞及处理
    Mybatis中的CDATA标签
    idea运行固定多个模块项目
    理解Node.js事件驱动编程
  • 原文地址:https://www.cnblogs.com/zllwxm123/p/10782348.html
Copyright © 2020-2023  润新知