当前位置:网站首页>NC40 链表相加(二)

NC40 链表相加(二)

2022-08-09 13:02:00 syc596

NC40 链表相加(二)

链表相加(二)_牛客题霸_牛客网 (nowcoder.com)

2. 两数相加

2. 两数相加 - 力扣(LeetCode)


import java.util.*;
public class Solution {
    public ListNode reverse(ListNode head){
        ListNode prev=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=prev;
            prev=cur;
            cur=next;
        }
        return prev;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        head1=reverse(head1);
        head2=reverse(head2);
        ListNode vhead=new ListNode(-1);
        ListNode cur=vhead;
        int carry=0;
        while(head1!=null||head2!=null){
            int x=(head1==null)?0:head1.val;
            int y=(head2==null)?0:head2.val;
            int sum=x+y+carry;
            carry=sum/10;
            sum=sum%10;
            cur.next=new ListNode(sum);
            cur=cur.next;
            if(head1!=null){
                head1=head1.next;
            }
            if(head2!=null){
                head2=head2.next;
            }
        }
        if(carry==1){
            cur.next=new ListNode(carry);
        }
        return reverse(vhead.next);
    }
}

原网站

版权声明
本文为[syc596]所创,转载请带上原文链接,感谢
https://blog.csdn.net/A240428037/article/details/126189393