首先这个题意刚开始还没搞明白。。。后面结果发现其实是:342+465=807
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/** * 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 head=new ListNode(0); ListNode p=l1,q=l2,currNode=head; int carry=0; while(p!=null||q!=null){ int x=(p!=null)?p.val:0; int y=(q!=null)?q.val:0; int sum=x+y+carry; int digit=sum; carry=sum/10; if(p!=null)p=p.next; if(q!=null)q=q.next; currNode.next=new ListNode(digit); currNode=currNode.next; } if(carry>0){ currNode.next=new ListNode(carry); } return head.next; } }
算法中需要注意地方是:最后进位的判断以及设置首节点的必要性:否则新建节点currNode.next=new ListNode(0)会导致最后多出来一个节点,如7->0->8->0;