LeetCode 2 - Add Two Numbers

来源:互联网 发布:软件测试报告缺陷总结 编辑:程序博客网 时间:2024/06/04 19:35

Add Two Numbers

题目链接

https://leetcode.com/problems/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

解题思路

创建一个新链表作为返回,同时遍历L1和L2,手工实现十进制加法,结果采用尾插法写入新链表

Tips:
1. L1和L2可能长度不同,需对空结点进行处理
2. 最后一位可能产生进位,需单独处理

代码实现(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) {        ListNode* L = new ListNode(-1);     // 新链表头结点        ListNode* p = L;    // 工作指针        int ca = 0;    // 进位标记        int v1, v2, sumValue, realValue;        while (l1 || l2) {            v1 = l1 ? l1->val : 0;            v2 = l2 ? l2->val : 0;            sumValue = v1 + v2 + ca;            realValue = sumValue % 10;            ca = sumValue / 10;            l1 = l1 ? l1->next : nullptr;            l2 = l2 ? l2->next : nullptr;            p->next = new ListNode(realValue);            p = p -> next;        }        if (ca > 0) {            p -> next = new ListNode(ca);        }        return L -> next;    }};

效率

对两个链表均只遍历一遍,时间复杂度: O(n)
需要生成新的链表,空间复杂度: O(n)

0 0
原创粉丝点击