LeetCode 2 — Add Two Numbers(C++ Java Python)

该博客介绍了LeetCode上的第2道题,即如何将两个存储为链表形式的逆序非负数相加。题目要求处理进位,返回结果仍以链表形式给出。博客中提供了C++、Java和Python三种语言的实现方案。
摘要由CSDN通过智能技术生成

题目:http://oj.leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. 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.

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

题目翻译:

给定两个链表表示两个非负数。数字逆序存储,每个节点包含一个单一的数字。计算两个数的和,并以链表的形式返还。

分析:

        要考虑进位。表示结果的结点要new出来。

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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.

		if (l1 == NULL)
		{
			return l2;
		}
		if (l2 == NULL)
		{
			return l1;
		}

		ListNode *result = NULL;
		ListNode *sum = NULL;

		int val = 0;
		int carry = 0;

		while (l1 != NULL || l2 != NULL)
		{
			val = carry;
			if (l1 != NULL)
			{
				val += l1->val;
			}
			if (l2 != NULL)
			{
				val += l2->val;
			}

			carry = val / 10;
			val -= carry * 10;

			if (sum == NULL)
			{
				sum = new ListNode(val);
				result = sum;
			}
			else
			{
				sum->next = new ListNode(val);
				sum = sum->next;
			}

			if (l1 != NULL)  
			{
				l1 = l1->next;
			}
			if (l2 != NULL)
			{
				l2 = l2->next;
			}
		}

		if (carry != 0)
		{
			sum->next = new ListNode(carry);
		}

		return result;
    }
};

Java实现:(与C++实现不太一样)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if (l1 == null) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}

		int len1 = 0;
		int len2 = 0;

		ListNode head = l1;

		while (head != null) {
			++len1;
			head = head.next;
		}

		head = l2;

		while (head != null) {
			++len2;
			head = head.next;
		}

		ListNode longer = len1 >= len2 ? l1 : l2;
		ListNode shorter = len1 < len2 ? l1 : l2;

		ListNode result = null;
		ListNode sum = null;

		int val = 0;
		int carry = 0;

		while (shorter != null) {
			val = longer.val + shorter.val + carry;
			carry = val / 10;
			val -= carry * 10;
			
			if (sum == null) {
				sum = new ListNode(val);
				result = sum;
			} else {
				sum.next = new ListNode(val);
				sum = sum.next;
			}
			
			longer = longer.next;
			shorter = shorter.next;
		}

		while (longer != null) {
			val = longer.val + carry;
			carry = val / 10;
			val -= carry * 10;
			
			sum.next = new ListNode(val);
			sum = sum.next;
			
			longer = longer.next;
		}

		if (carry != 0) {
			sum.next = new ListNode(carry);
		}

		return result;
    }
}

Python实现:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        
        len1 = 0
        len2 = 0
        
        head = l1
        while head != None:
            len1 += 1
            head = head.next
        
        head = l2
        while head != None:
            len2 += 1
            head = head.next
        
        if len1 >= len2:
            longer = l1
            shorter = l2
        else:
            longer = l2;
            shorter = l1
        
        sum = None
        
        carry = 0
        
        while shorter != None:
            value = longer.val + shorter.val + carry
            carry = value / 10
            value -= carry * 10
            
            if sum == None:
                sum = ListNode(value)
                result = sum
            else:
                sum.next = ListNode(value)
                sum = sum.next
                
            longer = longer.next
            shorter = shorter.next
            
        while longer != None:
            value = longer.val + carry
            carry = value / 10
            value -= carry * 10
            
            sum.next = ListNode(value)
            sum = sum.next
            
            longer = longer.next
            
        if carry != 0:
            sum.next = ListNode(carry)
        
        return result

        感谢阅读,欢迎评论!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值