题目来源
题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
题目解析
将链表转换为整数,进行求和计算,然后将整数又转换为链表即可
题目解答
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Plus {
public ListNode plusAB(ListNode a, ListNode b) {
//将链表转换为整数
int aValue=listNodeConvertIntValue(a);
int bVlaue=listNodeConvertIntValue(b);
//计算求和
int sumValue=aValue+bVlaue;
//将整数转换为链表
return intValueConvertListNode(sumValue);
}
private int listNodeConvertIntValue(ListNode node){
StringBuilder sb=new StringBuilder();
ListNode cur=node;
while(cur!=null){
sb.append(cur.val);
cur=cur.next;
}
return Integer.parseInt(sb.reverse().toString());
}
private ListNode intValueConvertListNode(int value){
char[] ch=String.valueOf(value).toCharArray();
ListNode node=new ListNode(Integer.parseInt(String.valueOf(ch[ch.length-1])));
ListNode cur=node;
//整数反转存储到链表中
for(int i=ch.length-2;i>=0;i--){
ListNode newNode=new ListNode(Integer.parseInt(String.valueOf(ch[i])));
cur.next=newNode;
cur=newNode;
}
return node;
}
}