两个链表生成相加链表

采用大数加法的思想,将链表head1和链表head2中的节点数据分别取出来形成字符串,再判断字符串的大小,最终使用加法运算。包括进位等。
最后的出来的结果放到新链表中(思想很清晰,但是时间复杂度度较高)

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        StringBuffer sb=new StringBuffer();
        String s="";
        String t="";
        if(head1 == null)
            return head2;
        if(head2 == null){
            return head1;
        }
        while(head1!=null){
            s+=head1.val;
            head1=head1.next;
        }
        while(head2!=null){
            t+=head2.val;
            head2=head2.next;
        }
        int slength=s.length();
        int tlength=t.length();
        while(slength<tlength){
            s="0"+s;
            slength++;
        }
        while(tlength<slength){
            t="0"+t;
            tlength++;
        }
        int carry=0;
        for(int i=0;i<slength;i++){
            int num=s.charAt(slength-1-i)-'0'+t.charAt(slength-1-i)-'0'+carry;//charAt(i)是字符串中的第i个字符,
            //s.charAt(i)就是S中的第i个字符,因为字符都是用ASCII码存储的,存储的事ASCII码值,
            //用s.charAt(i)减去字符‘0’,就是用s.charAt(i)的码值减去‘0’的码值,
            //得到的值干好就是s中第i个字符的十进制值。所以该句是判断s中第i个字符的十进制值是否等于digit
            sb.append(num%10);
            carry=num/10;
        }
        if(carry!=0){
            sb.append(carry);
        }
        String sum=sb.toString();
        ListNode head = new ListNode(-1);//创建新链表
        ListNode nHead = head.next;
        for(int i=0;i<sum.length();i++){
            int j=sum.charAt(i)-'0';
            ListNode node = new ListNode(j);
            node.next = nHead;
            nHead = node;
        }
        return nHead;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忆初0728

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值