zoukankan      html  css  js  c++  java
  • Lintcode: Add Two Numbers

    C++

     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     /**
    12      * @param l1: the first list
    13      * @param l2: the second list
    14      * @return: the sum list of l1 and l2 
    15      */
    16     ListNode *addLists(ListNode *l1, ListNode *l2) {
    17         // write your code here
    18         if (l1 == NULL) {
    19             return l2;
    20         }
    21         if (l2 == NULL) {
    22             return l1;
    23         }
    24         ListNode *ptr1 = l1, *ptr2 = l2;
    25         ListNode *result = new ListNode(-1);
    26         ListNode *pre = result;
    27         int carry = 0, val = 0;
    28         while (ptr1 != NULL || ptr2 != NULL) {
    29             int val1 = ptr1 == NULL?0:ptr1->val;
    30             int val2 = ptr2 == NULL?0:ptr2->val;
    31             int sum = val1 + val2 + carry;
    32             val = sum;
    33             carry = sum/10;
    34             pre->next = new ListNode(val);
    35             pre = pre->next;
    36             if (ptr1!=NULL)
    37             {
    38                 ptr1 = ptr1->next;
    39             }
    40             if (ptr2!=NULL) 
    41             {
    42                 ptr2 = ptr2->next;
    43             }
    44         }
    45         if (carry == 1) {
    46             pre->next = new ListNode(1);
    47         }
    48         return result->next;
    49     }
    50 };
  • 相关阅读:
    Binary Search Tree Iterator 解答
    Invert Binary Tree 解答
    Min Stack 解答
    Trapping Raining Water 解答
    Candy 解答
    Jump Game II 解答
    Implement Hash Map Using Primitive Types
    Gas Station 解答
    Bucket Sort
    HashMap 专题
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/4998800.html
Copyright © 2011-2022 走看看