【leetcode】Add Two Numbers

来源:互联网 发布:手机版淘宝店铺收藏 编辑:程序博客网 时间:2024/06/04 17:55

描述:

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

实现:

/** * 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) {                /*异常输入*/        if(l1 == NULL)        {            return l2;        }        else if(l2 == NULL)        {            return l1;        }                /*两个链表的结点值相加,用l1存储和结点*/        ListNode *p = l1, *q = l2;        ListNode *last = l1;        int carry = 0;        while(p != NULL && q != NULL)        {            p->val += (q->val+carry);            carry = p->val/10;            p->val %= 10;                        last = p;            p = p->next;            q = q->next;        }                /*l2的数比l1大,将剩余的高位结点连缀至l1尾部*/        if(q != NULL)        {            last->next = q;            p = q;        }                /*只考虑剩余高位结点数字和进位的和*/        while(p != NULL)        {            p->val += carry;                        /*某一低位和进位的和未超过10,则后续高位不会因为进位而进一步产生进位*/            if(p->val < 10)            {                carry = 0;/*注意:一定要置零*/                break;            }                        carry = p->val/10;            p->val %= 10;                        last = p;            p = p->next;        }                /*当高位结点用完,还有进位时,开辟一个新的结点*/        if(carry != 0)        {            ListNode *tmp = (ListNode*)malloc(sizeof(ListNode));            tmp->val = carry;            tmp->next = NULL;                        last->next = tmp;        }                return l1;            }};

分析:

时间复杂度:O(m+n)

空间复杂度:O(1)

0 0
原创粉丝点击