LeetCode 刷题记录 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.
答案:

方法1:
思路:遍历两个两个链表,得到num1和num2,然后得到它们的和,用尾插法得到链表
注意点:

  1. 数字位数可能很多,要用long long 存储(但仍有部分测试点过不去,未想到方法)
  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) {
        long long num1 = 0;
        long long num2 = 0;
        long long factor = 1;
        while(l1 != nullptr || l2 != nullptr){
            num1 = ((l1 == nullptr) ? 0 : l1 -> val) * factor + num1;
            num2 = ((l2 == nullptr) ? 0 : l2 -> val) * factor + num2;
            if(l1 != nullptr){
                l1 = l1 -> next;
            }
            if(l2 != nullptr){
                l2 = l2 -> next;
            }
            
            factor *= 10;
            
        }
        long long ans = num1 + num2;
        //头结点
        ListNode ansList(-1);
        
        ListNode* pre = &ansList;
        //头插法
        /*
        while(ans){
            ListNode* temp = new ListNode(ans % 10);
            temp -> next = pre -> next;
            pre -> next = temp; 
            ans /= 10;
            
        }
        */
        //尾插法
        while(ans){
            ListNode* temp = new ListNode(ans % 10);
            
            pre -> next = temp; 
            pre = temp;
            ans /= 10;
            
        }
        
        return ansList.next;
        
        
    }
};

方法2:
由于链表是逆序排列,所以可以在遍历的过程中直接对应为相加,然后尾插法构建链表,注意carry表示进位
C++版:

  1. 判断时注意carry也要不等于空 以免漏掉最后的进位
  2. 不建议写
    ListNode *dummy = new ListNode(-1), *cur;
    curr = dummy;

    return dummy->next;
    会造成内存泄漏,指针未释放
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        //头结点
        ListNode dummy(-1);
        //指向头结点的指针
        ListNode* cur = &dummy;
        //储存进位
        int carry = 0;
        while(l1 != nullptr || l2 != nullptr || carry != 0){
            if(l1 != nullptr){
                carry += l1 -> val;
                l1 = l1 -> next;
            }
            if(l2 != nullptr){
                carry += l2 -> val;
                l2 = l2 -> next;
            }
            //尾插法
            ListNode* temp = new ListNode(carry % 10);
            cur -> next = temp;
            cur = temp;
            carry /= 10;
        }
        return dummy.next;
        
        
    }
};

Java版:
与C++不同点

  1. java没有指针,故没有-> 只有.运算符
  2. java写法:ListNode dummy = new ListNode(-1);
  3. C++写法:ListNode dummy(-1); ListNode* cur = new ListNode(num); new出来是指针
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        int carry = 0;
        while(l1 != null || l2 != null || carry != 0){
            if(l1 != null){
                carry += l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                carry += l2.val;
                l2 = l2.next;
            }
            cur.next = new ListNode(carry % 10);
            cur = cur.next;
            carry /= 10;
        }
        return dummy.next;
        
    }
}

Python:
注意:

  1. while循环是or
  2. //表示整数除法 /表示浮点数除法
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = cur = ListNode(-1)
        carry = 0
        while l1 or l2 or carry:
            if l1:
                carry += l1.val
                l1 = l1.next
            if l2:
                carry += l2.val
                l2 = l2.next
            cur.next = ListNode(carry % 10)
            cur = cur.next
            
            carry //= 10
        return dummy.next
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值