java牛客网 链式A+B

题目:两个链表,存储两个整数。
整数的个位数是首节点。逆序存储在链表中。
两个整数相加的和用链表返回。(注意也是逆序存储)

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;
    }

猜你喜欢

转载自blog.51cto.com/14232658/2456760