两个链表生成相加链表

描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
复制
返回值:
{1,0,0,0}

public class 两个链表生成相加链表 {

     public class ListNode {
       int val;
       ListNode next = null;

         public ListNode(int i) {
             val = i;
         }
     }
//    public ListNode addInList (ListNode head1, ListNode head2) {
//        // write code here
//        StringBuilder sb1 = new StringBuilder();
//        while(head1 != null){
//            sb1.append(head1.val);
//            head1 = head1.next;
//        }
//        StringBuilder sb2 = new StringBuilder();
//        while(head2 != null){
//            sb2.append(head2.val);
//            head2 = head2.next;
//        }
//        String result = String.valueOf(new BigDecimal(sb2.toString()).add(new BigDecimal(sb1.toString())).toPlainString());
//        System.out.println(result);
//        ListNode temp = new ListNode(-1);
//        ListNode curr = new ListNode(result.charAt(0) - 48);
//        for(int i = 1; i < result.length();i++){
//            curr.next = new ListNode(result.charAt(i) - 48);
//            curr = curr.next;
//        }
//        return temp.next;
//    }

    public ListNode reverse(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode pre = null, curr = head;
        while(curr != null){
            ListNode temp = curr.next;
            curr.next = pre;
            pre = curr;
            curr = temp;
        }
        return pre;
    }

    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        ListNode h1 = reverse(head1), h2 = reverse(head2);
        ListNode temp = new ListNode(-1);
        ListNode curr = temp;
        boolean flag = false;
        int t = 0;
        while(h1 != null || h2 != null){
            int node1 = h1 != null ? h1.val : 0;
            int node2 = h2 != null ? h2.val : 0;
            int total = node1 + node2;
            if(flag){
                total += 1;
            }
            if(total / 10 > 0){
                flag = true;
            }else{
                flag = false;
            }
            curr.next = new ListNode(total % 10);
            if(h1 != null){
                h1 = h1.next;
            }

            if(h2 != null){
                h2 = h2.next;
            }
            curr = curr.next;
        }
        if(flag){
            curr.next = new ListNode(1);
        }
        return reverse(temp.next);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值