package com.JackChen.leetCode.Day1;
import java.util.Scanner;
/**
* 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
* 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
* 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
* 示例:
* 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
* 输出:7 -> 0 -> 8
* 原因:342 + 465 = 807
*
* @author Jack Chen
*
*/
public class AddTwoNumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {//键盘获取2个字符串以空格隔开
String firstInput = scanner.nextLine();
String secondInput = scanner.nextLine();
//构建链表
ListNode node1 = creatListNode(firstInput);
ListNode node2 = creatListNode(secondInput);
//打印链表
print(addTwoNumbers(node1, node2));
}
}
private static ListNode addTwoNumbers(ListNode node1, ListNode node2) {
// TODO Auto-generated method stub
ListNode node = new ListNode();//创建一个链表
ListNode cur = node;//使用操作cur,因为操作完链表后,没有办法再次找到链表的头部
int temp = 0;//进位
while(node1 != null || node2 != null) {//只要有一个链表不为空,就需要计算
int val1 = node1 == null ? 0 : node1.val;
int val2 = node2 == null ? 0 : node2.val;
int sum = val1 + val2 + temp;
temp = sum/10;
cur.next = new ListNode(sum%10);
cur = cur.next;
node1 = node1 == null ? null : node1.next;
node2 = node2 == null ? null : node2.next;
}
if (temp != 0) {
cur.next = new ListNode(temp);
}
return node.next;
}
private static ListNode creatListNode(String input) {
// TODO Auto-generated method stub
ListNode temp = new ListNode();
ListNode node = temp;
String[] arrays = input.split(" ");
for (int i = 0; i < arrays.length; i++) {
temp.next = new ListNode(Integer.parseInt(arrays[i]));
temp = temp.next;
}
return node.next;
}
public static void print(ListNode node) {
while(node != null) {
System.out.print(node.val);
node = node.next;
}
}
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;
}
}
}
力扣-两数相加
最新推荐文章于 2024-08-04 17:16:44 发布