链表相加(二)

链表相加可以先使链表进行反转再进行相加,先设一个头节点,之后对链表进行相加,所得值可以new一个头节点%10进行存放,注意最后相加之后可能会多出来一个1.

public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        head1=reverse(head1);
        head2=reverse(head2);
        ListNode h=new ListNode(0);
        ListNode h0=h;
        int tmp=0;
        while (head1!=null||head2!=null){
            int val=tmp;
            if(head1!=null){
                val+=head1.val;
                head1=head1.next;
            }
            if(head2!=null){
                val+=head2.val;
                head2=head2.next;
            }
            
            h0.next=new ListNode(val%10);
            h0=h0.next;
            tmp=val/10;
        }
        if(tmp!=0){
            h0.next=new ListNode(tmp);
        }
        return reverse(h.next);
    }
    
    public ListNode reverse(ListNode head){
        if(head==null) return head;
        ListNode cur=head;
        ListNode pre=null;
        while (cur!=null){
            ListNode tail=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tail;
        }
        return pre;
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务