[算法面试题]链表求和

给定两个用链表表示的整数,每个节点包含一个数位。

这些数位是反向存放的,也就是个位排在链表首部。

编写函数对这两个整数求和,并用链表形式返回结果。

示例:

输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?

示例:

输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912

进阶答案:先将两个链表翻转相加,最后再将结果翻转过来

public class Main {
    //非空链表
    //5-6
    //6-6-6
    //  5-6
    //7-2-2
    public static void main(String[] args) {
        String a = "abc";
        boolean a1 = a.contains(String.valueOf('a'));
    }
    //链表相加
    ListNode addListNode(ListNode listNode1, ListNode listNode2){
        int lev = 0;
        ListNode res = new ListNode(-1);
        ListNode dummyHead = res;
        while (listNode1 != null || listNode2 != null){
            int num1 = listNode1 == null ? 0 : listNode1.val;
            int num2 = listNode2 == null ? 0 : listNode2.val;
            int sum = num1 + num2 + lev;
            lev = sum / 10;
            res.next = new ListNode(sum % 10);
            listNode1 = listNode1 == null ? null : listNode1.next;
            listNode2 = listNode2 == null ? null : listNode2.next;
            res = res.next;
        }
        if (lev == 1){
            res.next = new ListNode(1);
        }
        return dummyHead.next;
    }

    //反转链表
    //1-2-3
    ListNode reverseListNode(ListNode head){
        if (head == null || head.next == null){
            return head;
        }
        ListNode next = reverseListNode(head.next);
        head.next.next = head;
        head.next = null;
        return next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值