LeetCode腾讯精选练习50题--1.两数相加
一、题目
二、题目解析
本题大意为两个链表的同一位置数相加,形成一个新的链表
对于示例1来说 [2,4,3] [5,6,4]
相加可视化即为243 + 564 = 807;
新的链表倒序显示,即为 [7,0,8]
需要注意的是,数据不大于10,即超过10要进一到下一个节点相加,或者 增加一个val为 1的节点
三、代码部分
/** * Definition for singly-linked list. * public 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) { ListNode result = null, temp = null; int carry = 0; while(l1 != null || l2 != null){ //两个链表循环 int a = l1 != null ? l1.val : 0; //判断链表当前节点的值是否为空,不为空取val int b = l2 != null ? l2.val : 0; int result1 = a + b + carry; //carry为上一次相加的进位 if(result == null){ result = temp = new ListNode(result1 % 10); }else{ temp.next = new ListNode(result1 % 10); temp = temp.next; //链表拼接 } carry = result1 / 10; if(l1 != null) l1 = l1.next; if(l2 != null) l2 = l2.next; } if(carry > 0){ //最后一次相加carry不为0 新建节点 temp.next = new ListNode(carry); } return result; } }