LeetCode Solution | 2. Add Two Numbers(Simulation C++)

Description

LeetCode Problem Link

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.

Algorithm

Use variables to track carry and simulate the bitwise addition process starting from the header

  • Time complexity: O ( m a x ( n , m ) ) O(max(n, m))
  • Space complexity: O ( m a x ( n , m ) ) O(max(n, m))

C++ Solution

/**
 * 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) {        
        // Use variables to track carry
        // Simulate the bitwise addition process starting from the header
        auto p = l1, q = l2, dummy = new ListNode(-1);
        auto curr = dummy;
        int t = 0;
        
        while (p || q || t) {
            int sum = t;
            if (p) {sum += p->val; p = p->next;}
            if (q) {sum += q->val; q = q->next;}
            
            curr->next = new ListNode(sum % 10);
            curr = curr->next;
            t = sum / 10;
        }
        curr->next = NULL; // Actually constructor defined it
        
        return dummy->next;
    }
};

A-summary-about-how-to-solve-Linked-List-problem-C++

发布了308 篇原创文章 · 获赞 149 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104716864