LeetCode--Add Two Numbers

来源:互联网 发布:中世纪2全面战争优化9 编辑:程序博客网 时间:2024/05/19 03:25

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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 *head=new ListNode(0);        ListNode *ptr=head;        int carry=0;        while(true)        {            if(l1!=NULL)            {                carry+=l1->val;                l1=l1->next;            }            if(l2!=NULL)            {                carry+=l2->val;                l2=l2->next;            }            ptr->val=carry%10;            carry/=10;            if(l1!=NULL||l2!=NULL||carry!=0)            {                ptr->next=new ListNode(0);                ptr=ptr->next;            }            else                break;        }        return head;    }};