Leetcode 第2题Add Two Numbers

来源:互联网 发布:mac 不能玩炉石传说么 编辑:程序博客网 时间:2024/05/21 09:24

题目: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


题目含义:

  • 就是两个链表的数字例如342和465,然后相加;唯一需要注意的是有无进位

思路:

  • 两个指针分别指向两个链表,然后相加,注意有进位;
  • 最后当其中一个链表结束后,直接将另一个链表的末尾加入;
  • 等两个链表都结束后需要注意进位标志是否为1;如果为1还需要添加一个链表的next

代码:

  • C++:
/** * 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) {        int flag=0;//定义一个标志位 用于判断是否有进位需求        ListNode* res=new ListNode(0);//初始化一个链表        ListNode* p=res;//定义一个指针        while(l1 != NULL || l2 != NULL)        {            int val1=0;            if(l1 != NULL)            {                val1=l1->val;                l1=l1->next;            }            int val2=0;            if(l2 != NULL)            {                val2=l2->val;                l2=l2->next;            }            int temp=val1+val2+flag;            p->next=new ListNode(temp%10);            flag=temp/10;            p=p->next;        }        if(flag==1)//如果最后还有进位 那么需要再链表的最后增加一个指针并且其值为1        {            p->next=new ListNode(1);        }        return res->next;    }};
0 0