首页 > 代码库 > [leetcode] 2. Add Two Numbers

[leetcode] 2. 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

Solution: link list

简单,注意两点:

1. 加到最后,可能还有进位

2. 链表实现时,可以多申请一个node的空间为x,返回x.next,可使代码更简洁。

#include <iostream>#include <vector>//  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 out = ListNode(0);        ListNode *tail = &out;        if(!l1 || !l2)        {            return NULL;        }        int carry = 0;        while(l1 && l2)        {            int s = carry + l1->val + l2->val;            carry = s / 10;            s = s % 10;            l1 = l1->next;            l2 = l2->next;            ListNode *temp = new ListNode(s);            tail->next = temp;            tail = tail->next;        }        if(l2)        {            l1 = l2;        }        while(l1)        {            int s = l1->val + carry;            carry = s / 10;            s = s % 10;            l1 = l1->next;            ListNode *temp = new ListNode(s);            tail->next = temp;            tail = tail->next;        }        if(carry)        {            ListNode *temp = new ListNode(carry);            tail->next = temp;            tail = tail->next;        }        return out.next;    }};