题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        return reverse(add(reverse(head1),reverse(head2)));
    }

    public ListNode add(ListNode head1, ListNode head2){
        if(head1==null){
            return head2;
        }
        if(head2==null){
            return head1;
        }
        ListNode tmp1 = head1;
        ListNode tmp2 = head2;
        ListNode tail = head1;
        int jw=0;
        boolean flag = true;
        while(head1!=null || head2!=null){
            int l1 = head1!=null?head1.val:0;
            int l2 = head2!=null?head2.val:0;
            int tmp = l1+l2+jw;
            jw=0;
            if(tmp>9){
                jw =1;
            }
            tmp = tmp%10;
            if(head1!=null){
                tail = head1;
                flag = true;
                head1.val = tmp;
                head1 = head1.next;
            }
            if(head2!=null){
                tail = head2;
                flag = false;
                head2.val = tmp;
                head2 = head2.next;
            }
        }
        if(jw>0){
            tail.next = new ListNode(1);
        }

        return flag?tmp1:tmp2;
    }

    public ListNode reverse(ListNode head){
        if(head==null){
            return head;
        }
        ListNode l1 = head;
        ListNode l2 = head.next;
        while(l1 != null){
            if(l2==null){
                head.next = null;
                return l1;
            }
            ListNode tmp = l2.next;
            l2.next = l1;
            l1 = l2;
            l2 = tmp;
        }
        return l1;
    }




}

全部评论

相关推荐

都来卷JAVA,卷④tmd😂😂
喝茶写代码:Java真太卷了,一片红海,我和身边双9电子信息转Java的人都没有大厂后端的offer,甚至很多简历都过不去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务