[LeetCode] 2. Add Two Numbers

来源:互联网 发布:lrc歌词编辑器 mac 编辑:程序博客网 时间:2024/05/23 17:20

2. 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.

思路

  • 反序链表求和,首位为个位,由此相加向前进位。关键在于链表结构的用法,注意空指针问题。
  • 复杂性分析:
    • 时间复杂度:O(n).
    • 空间复杂度:O(1).

题解

/** * 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 *pl1 = l1;        ListNode *pl2 = l2;        // 建立非空结点,避免空指针        ListNode *current = new ListNode(0);        ListNode *head = current;        int carry = 0;        while (pl1 != NULL || pl2 != NULL) {            int sum = 0;            if (pl1 != NULL) {                sum += pl1->val;                pl1 = pl1->next;            }            if (pl2 != NULL) {                sum += pl2->val;                pl2 = pl2->next;            }            sum += carry;            carry = sum / 10;            // 建立新结点,将指针指向新结点            current->next = new ListNode(sum % 10);            current = current->next;        }        if (carry) {            current->next = new ListNode(carry);        }        // 第一个结点无意义,真正的结果从下一结点开始        return head->next;    }};

优化

反思

  1. 没有考虑到空链表问题,导致操作空指针的错误。
    解决方法:1)分问题分点讨论,以排除空指针操作;2)添加头指针。
  2. 熟悉链表的生成和操作。
    生成:建立头指针 -> 生成新的有效结点 -> 将头指针和新结点相连。
  3. 分清 ListNode 和 ListNode* 的区别。
    ListNode 是结构体,包括声明函数和值。声明的时候用 ListNode* 声明指针的生成。

以上反思,有待指教。

原创粉丝点击