leetcode 2. Add Two Numbers

    技术2025-11-03  25

    Add Two Numbers /** * 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; int carry =0; ListNode tmp= null; ListNode tmp1= l1; ListNode tmp2= l2; int v1; int v2; while(tmp1!=null | tmp2!=null){ if(tmp1==null){ v1=0; } else{ v1=tmp1.val; } if(tmp2==null){ v2=0; }else{ v2=tmp2.val; } if(result==null){ result= new ListNode((v1+v2)%10,null); carry =(v1+v2)/10; tmp=result; } else { tmp.next=new ListNode((v1+v2+carry)%10,null); carry=(v1+v2+carry)/10; System.out.println(tmp.val); tmp=tmp.next; } if(tmp1!=null){ tmp1=tmp1.next;} if(tmp2!=null){ tmp2=tmp2.next;} } if(carry!=0){ tmp.next=new ListNode(1,null); } return result; } }
    Processed: 0.016, SQL: 9