码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-002-两数相加

时间:2020-02-20 17:11:36      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:reader   link   链表的操作   while   public   span   操作   leetcode   read   

本题主要是考查对链表的操作。

/**
 * 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 cur1 = l1;
        ListNode cur2 = l2;

        int temp = 0;

        ListNode init = new ListNode(0);
        ListNode cur = init;

        while(cur1!=null || cur2!=null){
            temp/=10;
            if(cur1!=null){
                temp += cur1.val;
                cur1 = cur1.next;
            }
            if(cur2!=null){
                temp += cur2.val;
                cur2 = cur2.next;
            }
            cur.next = new ListNode(temp%10);
            cur = cur.next;
        }
        if(temp/10!=0){
            cur.next = new ListNode(1);
        }

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

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur1 = l1
        cur2 = l2

        init = ListNode(0)
        cur = init

        temp = 0

        while cur1 is not None or cur2 is not None:

            temp //= 10;
            if cur1 is not None:
                temp+=cur1.val
                cur1 = cur1.next
            if cur2 is not None:
                temp+=cur2.val
                cur2 = cur2.next
            cur.next = ListNode(temp%10)
            cur = cur.next

        if temp//10!=0:
            cur.next = ListNode(1)
        return init.next

 

Leetcode-002-两数相加

标签:reader   link   链表的操作   while   public   span   操作   leetcode   read   

原文地址:https://www.cnblogs.com/huangzengrui/p/12336143.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!