java牛客網 鏈式A+B

題目:兩個鏈表,存儲兩個整數。
整數的個位數是首節點。逆序存儲在鏈表中。
兩個整數相加的和用鏈表返回。(注意也是逆序存儲)node

class ListNode{
    int val;
    ListNode next=null;
    ListNode(int val){
        this.val=val;
    }
}
    public   ListNode plusAB(ListNode a,ListNode b){
        int avalue=listNodeConvertIntValue(a);
        int bvalue=listNodeConvertIntValue(b);

        int sumValue=avalue+bvalue;
        return  intValueConvertListNode(sumValue);
    }

    public   int listNodeConvertIntValue(ListNode node){

StringBuffer sb=new StringBuffer();
ListNode cur=node;
while(cur!=null){
    sb.append(cur.val);
cur=cur.next;
}
return Integer.parseInt(sb.reverse().toString());//參數是字符串

}
    public   ListNode intValueConvertListNode(int value){

          char [] str=  String.valueOf(value).toCharArray();
          int length=str.length;

          ListNode node= new ListNode( Integer.parseInt(String.valueOf(str[length-1])));
          ListNode cur=node;//整數的最後一個位數做爲頭結點
          for(int i=str.length-1;i>=0;i--){
             ListNode newnode= new ListNode(Integer.parseInt(String.valueOf(str[i])));
                  cur.next=newnode;
                  cur=newnode;//個位數放在前面結點
          }
          return node;
    }
相關文章
相關標籤/搜索