LeetCode:2.两数相加(add two numbers)Java完整代码

2021/12/7 1:16:36

本文主要是介绍LeetCode:2.两数相加(add two numbers)Java完整代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

LeetCode:2.两数相加(add two numbers)
题解与思路
谁能想到,我居然被链表的输入给折磨了这么久!

import java.util.*;
/**
 * 在这里给出对类 LC2AddTwoNumbers 的描述。
 * 
 * @作者(yequan17)
 * @版本(2021.12.6)
 */
public class LC2AddTwoNumbers
{
    /**
     * Definition for singly-linked list.
     */
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String[] strs=sc.nextLine().split(",");
        String[] strs2=sc.nextLine().split(",");
        ListNode l1=new ListNode();
        ListNode nextNode;
        nextNode=l1;
        ListNode l2=new ListNode();
        ListNode nextNode2;
        nextNode2=l2;
        //循环为链表1赋值
        for(int i=0;i<strs.length;i++){
            ListNode node=new ListNode(Integer.parseInt(strs[i]));//生成新的节点
            nextNode.next=node;           //把节点连起来
            nextNode=nextNode.next;       //把当前节点往后移动
        }
        nextNode=l1;//重新赋值让它指向头节点
        //循环为链表2赋值
        for(int i=0;i<strs2.length;i++){
            ListNode node=new ListNode(Integer.parseInt(strs2[i]));//生成新的节点
            nextNode2.next=node;           //把节点连起来
            nextNode2=nextNode2.next;       //把当前节点往后移动
        }
        nextNode2=l2;//重新赋值让它指向头节点
        ListNode listNode=addTwoNumbers(l1,l2);
        //注意我们最开始定义的了l1其实是pre,目的是让它指向真正的head,所以应该从第二个节点开始输出
        listNode=listNode.next;
        System.out.print(listNode.val);
        listNode=listNode.next;
        while(listNode!=null){
            System.out.print(","+listNode.val);
            listNode=listNode.next;
        }
       
     }
    
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode head=null,tail=null;
        int carry=0;
        while(l1!=null||l2!=null){
            int n1=l1!=null?l1.val:0;
            int n2=l2!=null?l2.val:0;
            int sum=n1+n2+carry;
            if(head==null){
                head=tail=new ListNode(sum%10);
            }else{
                tail.next=new ListNode(sum%10);
                tail=tail.next;
            }
            carry=sum>9?1:0;
            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }
        }
        if(carry>0){
            tail.next=new ListNode(carry);
        }
        return head;
    }
}



这篇关于LeetCode:2.两数相加(add two numbers)Java完整代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程