[LeetCode]--Add Two Numbers

来源:互联网 发布:淘宝店铺等级 编辑:程序博客网 时间:2024/05/16 14:15

题目

    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

    中文题意:给出两个非空链表分别代表两个非负整数。数字按照逆序存储并且每个节点只包含单个数字。求两数的和并返回链表形式。

分析

         因为数字按照逆序存储,显然题中所给的示例中两数分别为:342,465。而342+465=807。因此最终返回数807的逆向存储列表7->0->8。
       刚开始在写这道题的时候,想当然地认为两个链表的长度相同。而这恰恰是我们思维的一个误区。题中并没有提及两链表的长度,因此有可能是不同的,这就需要事先判断指针是否指向null,即链表是否将为空,若为空则建立一个新的存储数字“0”的节点。
       解决了这个问题,这道题就很容易Pass了。我们先建立一个新列表result(将结果存储在其中),然后遍历两个给出列表中的对应节点并做加法运算。值得注意的是,两数相加若大于10,我们将利用取模(%)运算得到本位结果,利用除法(/)运算得到进位结果保存在carry中并在下一位的加法运算过程中加上carry。如果两链表的所有非空节点都已遍历完,且carry>0时,则需要新创建一个节点以保存运算结果的最高位。

解答

/** * 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* m=l1;         ListNode* n=l2;        ListNode* result=new ListNode(0);        ListNode* cur=result;        int carry=0;        int sum=0;        while(m!=NULL || n!=NULL){            if(m==NULL) {                m=new ListNode(0);            }            if(n==NULL) {                n=new ListNode(0);            }            sum=(m->val)+(n->val)+carry;            carry=sum/10;            //cout<<carry<<" "<<sum<<endl;            cur->next=new ListNode(sum%10);            cur=cur->next;            if(m!=NULL) m=m->next;            if(n!=NULL) n=n->next;            sum=0;        }        if(carry>0){            cur->next=new ListNode(carry);        }        return result->next;    }};

         不难得出,该算法的复杂度为O(max{l1.size(), l2.size()})

  

原创粉丝点击