LeetCode2: 两数相加

题目

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

Solution

双指针技巧,具体可参考https://labuladong.github.io/algo/2/19/18/

Code

  • Python
"""
https://leetcode.com/problems/add-two-numbers/solution/
思路的话就是快慢指针的额解法
"""
from typing import Optional

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

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        ret = ListNode(0)
        curr = ret
        carry = 0  # 用于获取计算结果多余的值,相加的余数
        while l1 != None or l2 != None or carry != 0:  # TODO 注意判断条件是啥
            l1Val = l1.val if l1 else 0
            l2Val = l2.val if l2 else 0
            print("l1Val:{},l2Val".format(l1Val, l2Val))
            carry = (l1Val + l2Val + carry) // 10
            newNode = ListNode((l1Val + l2Val + carry) % 10)
            curr.next = newNode
            curr = newNode
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return ret.next  # head为0



if __name__ == '__main__':
    S = Solution()
    o1 = [2, 4, 3]
    o2 = [5, 6, 4, 9]

    l1 = ListNode(o1[0])
    l1_curr = l1
    for i in range(1, len(o1)):
        newNode = ListNode(o1[i])
        l1_curr.next = newNode
        l1_curr = newNode       

    l2 = ListNode(o2[0])
    l2_curr = l2
    for i in range(1, len(o2)):
        newNode = ListNode(o2[i])
        l2_curr.next = newNode
        l2_curr = newNode

    ret = S.addTwoNumbers(l1, l2)
    print(ret)
    while ret != None:
        print("val:{}".format(ret.val))
        ret = ret.next if ret else None
  • java
import java.util.LinkedList;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//        System.out.printf("l1: %s", l1);
//        System.out.printf("l2: %s", l2);
        ListNode result = new ListNode();
        ListNode current = result;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            carry = sum / 10;
            current.next = new ListNode(sum % 10);
            current = current.next;
        }
        return result.next;
    }
}

public class AddTwoNumbers {
    public static void main(String[] args) {
//        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
//        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));

        LinkedList<Integer> l1 = new LinkedList<>();
        LinkedList<Integer> l2 = new LinkedList<>();
        int count = 0;
        while (count < 10) {
            l1.add((int) (Math.random() * 10));
            l2.add((int) (Math.random() * 10));
            count++;
        }

        ListNode l1Node = new ListNode();
        ListNode l1Current = l1Node;
        for (int i = 0; i < l1.size(); i++) {
            System.out.printf("l1: %d\t", l1.get(i));
            l1Current.val = l1.get(i);
            l1Current.next = new ListNode();
            l1Current = l1Current.next;
        }

        System.out.println("");

        ListNode l2Node = new ListNode();
        ListNode l2Current = l2Node;
        for (int i = 0; i < l2.size(); i++) {
            System.out.printf("l2: %d\t", l2.get(i));
            l2Current.val = l2.get(i);
            l2Current.next = new ListNode();
            l2Current = l2Current.next;
        }

        System.out.println("");

        ListNode l3 = new Solution().addTwoNumbers(l1Node, l2Node);
        while (l3 != null){
//            System.out.println(l3.val);
            System.out.printf("l3: %d\t", l3.val);
            l3 = l3.next;
        }
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *