力扣两数相加解法:
class Solution {
public ListNode addTwoNumbers(ListNode l1,ListNode l2) {
int cin = 0;int i=1;ListNode tempResult =new ListNode(0);
ListNode p = l1;ListNode q = l2;
ListNode result = tempResult;
while(p!=null||q!=null) {
int x = (p!=null)? p.val:0 ;
int y = (q!=null)? q.val:0 ;
int temp=x+y+cin;
tempResult.next=new ListNode(temp%10);
tempResult = tempResult.next;
cin = temp/10;
if(p!=null) {
p=p.next;
}
if(q!=null) {
q=q.next;
}
}
if(cin>0) {
tempResult.next=new ListNode(cin);
tempResult = tempResult.next;
}
return result.next;
}
}
/*链表定义*/
class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
注意点:1.ListNode需要初始化 ,即new ListNode(0) 否则会导致空指针异常
2.为了不改变传进来的参数,最好另外声明一个链表,使其指向参数头指针。
978

被折叠的 条评论
为什么被折叠?



