<LeetCode>Add Two Numbers

来源:互联网 发布:走台步的基本技巧 知乎 编辑:程序博客网 时间:2024/06/06 05:30

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


主要是在与控制好进位操作和内存的申请:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {        ListNode result(0);        ListNode *p = l1,                 *q = l2;        ListNode *r = &result;        int number,            rem,            temp = 0;        while(p || q)        {             number =(q ? q->val:0) + (p?p->val:0) + temp;            temp = number / 10;            rem = number % 10;            r->next = new ListNode(rem);//val = rem            r = r->next;            if(p)                p = p->next;            if(q)                q = q->next;        }        if(temp)        {            r->next = new ListNode(temp);            r = r->next;        }                     return result.next;    }};


原创粉丝点击