題目來源
題目描述
有兩個用鏈表表示的整數,每個結點包含一個數位。這些數位是反向存放的,也就是個位排在鏈表的首部。編寫函數對這兩個整數求和,並用鏈表形式返回結果。
給定兩個鏈表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;
}
}