• 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

    注意取指针时要判断是否为空。

    一般尾插入的话,用一个dummy结点。这样就可以不用特殊处理头指针了。

     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 public:
    11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    12         ListNode ret(0);
    13         ListNode *p = &ret;
    14         int carry = 0, v1, v2, s;
    15         
    16         while (l1 != NULL || l2 != NULL) {
    17             v1 = l1 ? l1->val : 0;
    18             v2 = l2 ? l2->val : 0;
    19             s = v1 + v2 + carry;
    20             carry = s / 10;
    21             p->next = new ListNode(s % 10);
    22             p = p->next;
    23             if (l1) l1 = l1->next;
    24             if (l2) l2 = l2->next;
    25         }
    26         if (carry > 0) {
    27             p->next = new ListNode(carry);
    28         }
    29         return ret.next;
    30     }
    31 };

     代码现在是越写越简洁了,好事。逻辑清晰了许多。

     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 public:
    11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    12         int carry = 0, v = 0;
    13         ListNode h(0), *p = &h;
    14         while (l1 || l2) {
    15             v = carry;
    16             if (l1) {
    17                 v += l1->val;
    18                 l1 = l1->next;
    19             } 
    20             if (l2) {
    21                 v += l2->val;
    22                 l2 = l2->next;
    23             }
    24             p->next = new ListNode(v % 10);
    25             p = p->next;
    26             carry = v / 10;
    27         }
    28         if (carry > 0) {
    29             p->next = new ListNode(carry);
    30         }
    31         return h.next;
    32     }
    33 };
  • 相关阅读:
    jvm client模式和server模式
    TOMCAT开启APR模式
    Spring MVC 关于controller的字符编码问题
    彻底解决Spring MVC 中文乱码 问题
    js中字符串拼接html
    分布式文件系统之MooseFS----介绍
    CopyFile函數詳解
    Delphi 接口使用中,对象生命周期管理,如何释放需要注意的问题
    年度调查 看看 2016 年 Go 语言调查结果
    Sleep(0)的作用
  • 原文地址:https://www.cnblogs.com/linyx/p/3777910.html
Copyright © 2020-2023  润新知