给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:2 , 4 ,3
5 ,6, 4
输出:7 0 8
原因:342 + 465 = 807
import java.util.Scanner;
class Solution {
public class ListNode {
int val;//数据
ListNode next;指针
ListNode(int x) { val = x; }
}
public ListNode creat(int[] num) {
ListNode head=new ListNode(0);
head.next=null;//创建头节点,并作为返回值
ListNode cur=head;
for(int i=0;i<num.length;i++) {
ListNode node=new ListNode(num[i]);
cur.next=node;
node.next=null;
cur=node;
}//创建链表,采用逆序存储,如123实际是321,按个位,十位,百位的顺序存储
return head;
}
public static void display(ListNode head) {
head=head.next;
while(head!=null) {
System.out.print(head.val);
head=head.next;
}
}//打印链表
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//两数相加
ListNode pre = new ListNode(0);//采用一个新的链表来存储和,pre为其头节点
ListNode cur = pre;
int carry = 0;//进位
while(l1 != null || l2 != null) {
int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;
int sum = x + y + carry;取出l1,l2对应位相加,没有则补零;
carry = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;//得到的和存入新节点,并指向下一个位置
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}//两个数长度不等,一个结束了另一个还在继续
if(carry == 1) {
cur.next = new ListNode(carry);//l1,l2计算完毕,如果还有进位,需创建新节点存储
}
return pre.next;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String str1 = sc.next().toString();
String[] arr = str1.split(",");
int[] x = new int[arr.length];
for(int k = 0; k<x.length;k++) {
x[k] = Integer.parseInt(arr[k]);
}
String str2 = sc.next().toString();
String[] ar = str2.split(",");
int[] y = new int[ar.length];
for(int k = 0; k<y.length;k++) {
y[k] = Integer.parseInt(ar[k]);
}
Solution solution=new Solution();
ListNode l1=solution.creat(x);
ListNode l2=solution.creat(y);
display(l1);
System.out.print("\n");
display(l2);
System.out.print("\n");
display(solution.addTwoNumbers(l1,l2));
}
}