Add Two Numbers(基于链表的两数相加)

来源:互联网 发布:所有a股票数据库 编辑:程序博客网 时间:2024/05/29 04:15

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

1.个人分析
由题意和示例可以看出,链表从第一个节点开始,依次表示非负数的个位、百位、千位等等。对链表每个节点进行相加操作也遵循正常的进位。最直接的做法是同时遍历两个链表,将每个节点进行相加,如果有进位,则对求和结果取余,并在下一节点求和时加1。

2.个人解法

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){    ListNode *res = new ListNode(0);//创建一个空节点作为结果链表的头节点    ListNode *resCur = res;    ListNode *cur1 = l1;    ListNode *cur2 = l2;    int carry = 0;      //进位值    //处理两链表相同长度的情况    while (cur1 && cur2){               int tmp = cur1->val + cur2->val + carry;        carry = tmp >= 10 ?1 : 0;        int unit =  tmp % 10;        ListNode *newNode = new ListNode(unit);        resCur->next = newNode;        resCur = newNode;        cur1 = cur1->next;        cur2 = cur2->next;    }    if(cur1){       //处理l1长度比l2长度更长的情况        while(cur1){            int tmp = cur1->val + carry;            carry = tmp >= 10 ?1 : 0;            cur1->val = tmp % 10;            resCur->next = cur1;            resCur = cur1;            cur1 = cur1->next;        }    }    else if(cur2){      //处理l2长度比l1长度更长的情况        while(cur2){            int tmp = cur2->val + carry;            carry = tmp >= 10 ?1 : 0;            cur2->val = tmp % 10;            resCur->next = cur2;            resCur = cur2;            cur2 = cur2->next;        }    }    //处理最高位进位情形    if(carry == 1){        ListNode *newNode = new ListNode(carry);        resCur->next = newNode;        resCur = newNode;    }    return res->next;}

该解法的时间复杂度为O(n),空间复杂度为O(n),但整体流程显得比较冗长。

3.参考解法

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){    ListNode preHead(0), *p = &preHead;    int extra = 0;    while (l1 || l2 || extra) {        if (l1) extra += l1->val, l1 = l1->next;        if (l2) extra += l2->val, l2 = l2->next;        p->next = new ListNode(extra % 10);        extra /= 10;        p = p->next;    }    return preHead.next;}

该解法的时间复杂度为O(n),空间复杂度为O(n),运行效率与第一种解法差不多,但整体代码更加精简。

4.总结
该问题虽然不难想出解法,但需要考虑很多的细节,比如不等长的情形处理,最高位进位的处理,所以想要一次就AC不太容易。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
0 0
原创粉丝点击