admin 管理员组

文章数量: 887007

leetcode两数相加(最简单思路)

class Solution {

public:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        int size1 = 1;

        int size2 = 1;

        int type = 0;//进位值

        ListNode*temp1 = l1;

        ListNode*temp2 = l2;

        while(temp1->next !=nullptr)

        {

            size1++;

            temp1 = temp1->next;

        }

         while(temp2->next !=nullptr)

        {

            size2++;

            temp2 = temp2->next;

        }

        ListNode*ptr1 = l1;

        ListNode*ptr2 = l2;

        if(size1>=size2)

        {

            for(int i =0;i<size1;i++)

            {

                int x;

                if(i<size2)

                    x = ptr1->val+ptr2->val+type;

                else

                    x = ptr1->val+type;

                if(x>=10)

                {

                    ptr1->val = x-10;

                    type = 1;

                }

                else

                {

                    ptr1->val = x;

                    type = 0;

                }

                ptr1 = ptr1->next;

                if(i<size2)

                    ptr2 = ptr2->next;

            }

            if(type == 1)

            {

                ListNode * ptr = new ListNode;

                ptr->val = 1;

                ListNode * temp = l1;

                for(int i=1;i<size1;i++)

                temp = temp->next;

                ptr->next=temp->next;

                temp->next = ptr;

            }

            return l1;

        }

        else

        {

            for(int i =0;i<size2;i++)

            {

                int x;

                if(i<size1)

                    x = ptr1->val+ptr2->val+type;

                else

                    x = ptr2->val+type;

                if(x>=10)

                {

                    ptr2->val = x-10;

                    type = 1;

                }

                else

                {

                    ptr2->val = x;

                    type = 0;

                }

                ptr2 = ptr2->next;

                if(i<size1)

                    ptr1 = ptr1->next;

            }

            if(type == 1)

            {

                ListNode * ptr = new ListNode;

                ptr->val = 1;

                ListNode * temp = l2;

                for(int i=1;i<size2;i++)

                temp = temp->next;

                ptr->next=temp->next;

                temp->next = ptr;

            }

            return l2;

        }

        return l1;

    }      

};

本文标签: leetcode两数相加(最简单思路)