LeetCode 2. Add Two Numbers(C++版)

本文介绍了一种使用链表来表示非负整数的方法,并详细解释了如何通过链表节点来实现两个整数的加法运算。具体地,文章提供了一个算法示例,该算法能在O(n)的时间复杂度内完成计算,同时也在原链表上进行操作以降低空间复杂度。

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路分析:

用非空链表存储两个整数的各个位,然后求这两个数的和。

直接重新申请了一个链表用来存储结果。

时间复杂度:O(n)

空间复杂度:O(n)

也可以在原链表上存储结果。但是需要判断l1、l2是否为空,代码比较繁琐。但空间复杂度可将为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) {
        //想加的结果存放在l1里,如果最后有进位,则new一个结点,然后插入到l1尾部
        int c = 0;//进位
        int sum = 0;//两个对应结点的和
        ListNode dummy_head(-1);
        ListNode *p = &dummy_head;
        //ListNode *dummy_head = new ListNode(-1);
        
        while(l1 != NULL || l2 != NULL){
            // int sum = cpl1 -> val + cpl2 -> val + c; 如果两个节点都不为空,sum的求法直接可用此式,但是需要考虑l1或者l2是否为空,所以分解求sum
            if(l1 != NULL){
                sum += l1 -> val;
                l1 = l1 -> next;
            }
            if(l2 != NULL){
                sum += l2 -> val;
                l2 = l2 -> next;
            }
            sum += c;
            
            p -> next = new ListNode(sum % 10);
            p = p -> next;
            c = sum / 10;
            sum = 0;
        }
        
       
        //判断最后的进位是否为0
        if( c == 1){
            p -> next = new ListNode(1);
        }
        return dummy_head.next;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值