解法思路:每次创建一个节点,其值等于相同位置上的l1和l2节点的值以及进位之和。若节点位null,其值为0,即可实现一致性。
/**
* 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 root = new ListNode(0);
ListNode purNode = root;
int tem=0;
int pursum=0;
int l1num,l2num;
while(l1!=null||l2!=null||tem!=0){
l1num= l1==null?0:l1.val;
l2num= l2==null?0:l2.val;
pursum = l1num+l2num;
ListNode pur=new ListNode();
pur.val= (pursum+tem)%10;
purNode.next=pur;
purNode = pur;
if(l1!=null){
l1=l1.next;}
if(l2!=null){
l2=l2.next;}
tem=(pursum+tem)/10;
}
return root.next;
}
}
踩坑:边界问题,tem!=0需要继续否则99999进1这类会出现问题。