题目来源:https://github.com/Blankj/awesome-java-leetcode/blob/master/note/002/README.md
是github上的一位作者分享的
解题思路:342+465=807
/**
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Explanation: 342 + 465 = 807.
*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class First {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//最终要输出的链表
ListNode node = new ListNode(0);
ListNode n1 = l1, n2 = l2, t = node;
int sum = 0;
while (n1 != null || n2 != null) {
//巧妙之处
sum /= 10;
if (n1 != null) {
sum += n1.val;
n1 = n1.next;
}
if (n2 != null) {
sum += n2.val;
n2 = n2.next;
}
//巧妙之处
t.next = new ListNode(sum % 10);
t = t.next;
}
//巧妙之处
if (sum / 10 != 0) t.next = new ListNode(1);
return node.next;
}
public static void main(String[] args)
{
First first=new First();
ListNode input1=new ListNode(2);
ListNode input2=new ListNode(4);
input1.next=input2;
ListNode input3=new ListNode(3);
input2.next=input3;
ListNode input11=new ListNode(5);
ListNode input12=new ListNode(6);
input11.next=input12;
ListNode input13=new ListNode(4);
input12.next=input13;
ListNode sum=first.addTwoNumbers(input1,input11);
while (sum!=null)
{
System.out.println(sum.val);
sum=sum.next;
}
}
}
class ListNode{
int val;
ListNode next;
ListNode(int x)
{
val=x;
}
}
输出:

网友评论