LeetCode 算法学习(1)

题目描述

Add Two Numbers
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.
Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目大意

求两个非空链表所代表的整数的和,并将其存储到一个链表中。

思路分析

这是一道比较简单的单链表题目,直接通过两个链表的同时遍历,数字相加,得到相应的进位(carry)值,再加到高一位的运算中,类似于串行的加法器原理。时间复杂度为O(Max(len1,len2)),空间复杂度也为O(Max(len1,len2))。

关键代码

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *itr1 = l1, *itr2 = l2;
        ListNode *result = new ListNode(-1);
        ListNode *itrResult = result;
        int carry = 0;
        while (itr1 != NULL && itr2 != NULL) { // 同时遍历
            int tempResult = itr1->val + itr2->val + carry;
            ListNode *tempNode = new ListNode(tempResult%10);
            itrResult->next = tempNode;
            itrResult = itrResult->next;
            carry = tempResult/10;
            itr1 = itr1->next;
            itr2 = itr2->next;
        }
        // 当两表长度不一样时
        while (itr1 != NULL) {
            int tempResult = itr1->val + carry;
            ListNode *tempNode = new ListNode(tempResult%10);
            itrResult->next = tempNode;
            itrResult = itrResult->next;
            carry = tempResult/10;
            itr1 = itr1->next;
        }
        while (itr2 != NULL) {
            int tempResult = itr2->val + carry;
            ListNode *tempNode = new ListNode(tempResult%10);
            itrResult->next = tempNode;
            itrResult = itrResult->next;
            carry = tempResult/10;
            itr2 = itr2->next;
        }
        // 最高位有进位
        if (carry != 0) {
            ListNode *tempNode = new ListNode(carry%10);
            itrResult->next = tempNode;
        }
        return result->next;
    }
};

总结

这道题虽然比较简单,但是在操作过程中和看完答案后,发现自己有几个问题:

1.代码过于冗余,表的长度不一样时其实可以合并到同一个循环内,即可以保证易读性,也可以提高一定的效率。
2. 在处理链表时不太熟练,不能快速地使用链表,没有考虑带头指针的链表。
3. 考虑到除法和取余数的操作可能相对会费时一点,这里应该也可以用减法提高一定的效率。

猜你喜欢

转载自blog.csdn.net/L_Realoo/article/details/85251032
今日推荐