[LeetCode]002. Add Two Numbers

本文介绍了一种解决链表加法问题的方法,通过将链表数值转换为整数相加,再将结果转换回链表形式。同时提供了一种更高效的两指针解法,直接在链表上进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Solution:

1. transfer node's value to each digit then combine to a long integer.

2. use math method to calculate.

3. transfer the result to digits and append to each node.

需要注意的是:

1. 计算数字的类型需要是long,否则无法通过大数据检测。

2. 在将数字转换并存储到Node中时,使用了append方法,这样有两次循环,运行时间似乎是O(n*n)?

这道题还有two pointers的解法,不过感觉我这种解法比较直观。


/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        long v1 = nodeToInt(l1);
        long v2 = nodeToInt(l2);
        long sum = v1 + v2;
        return intToNode(sum);
    }
    
    public long nodeToInt(ListNode n){
        Stack<Integer> st = new Stack<Integer>();
        while(n!=null){
            st.push(n.val);
            n = n.next;
        }
        long result = 0;
        while(!st.isEmpty()){
            result = result*10 + st.pop();
        }
        return result;
    }
    
    public ListNode intToNode(long number){
        String s = number + "";
        int len = s.length();
        int h = Character.getNumericValue(s.charAt(len-1));
        ListNode head = new ListNode(h);
        for(int i=len-2; i>=0; i--){
            ListNode n = head;
            ListNode end = new ListNode(Character.getNumericValue(s.charAt(i)));
            while(n.next != null){
                n = n.next;
            }
            n.next = end;
        }//append node here!!!
        return head;
    }
}


2015-03-14更新:

Python Solution: 链表的遍历,创建一个新的链表来储存计算好的值,注意链表l1和链表l2的长度区别,以及最后时段的进位。

Running Time: O(n)

# 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):
        dummy = ListNode(-1)
        p = dummy
        carry = 0
        while l1 and l2:
            temp = l1.val + l2.val + carry
            node_value = temp % 10
            carry = temp / 10
            p.next = ListNode(node_value)
            p = p.next
            l1 = l1.next
            l2 = l2.next
        while l1:
            temp = l1.val  + carry
            node_value = temp % 10
            carry = temp / 10
            p.next = ListNode(node_value)
            p = p.next
            l1 = l1.next
        while l2:
            temp = l2.val  + carry
            node_value = temp % 10
            carry = temp / 10
            p.next = ListNode(node_value)
            p = p.next
            l2 = l2.next
        if carry > 0:
            p.next = ListNode(carry)
        return dummy.next


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值