LeetCode之链表数相加

问题描述:

/**
 * You are given two linked lists representing two non-negative numbers. 
 * 
 * The digits are stored in reverse order and each of their nodes contain a single digit.
 * 
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 
 * Output: 7 -> 0 -> 8
 */

就是说有两个链表代表两个非负的整数,每一个链表节点都存储一个单个的数字,并且节点存储的顺序和整数的数字排列顺序是相反的,如上所示,数a为342,数b为465,相加为807.
解题思想还是从数的末尾开始相加,对于这道题来说也就是从两个链表的开头进行运算,期间要声明一个变量来作为进位。
这道题和我前面一篇博客是类似的,在进行运算时要对两个数“对齐”,即在对齐的情况下是一种运算,不对齐又是另一种情况。下面是代码:

public class AddTwoNumbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int plus = 0;
        while (l1 != null && l2 != null) {
            int sum = l1.val + l2.val + plus;
            plus = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        if (l1 != null) {
            if (plus != 0) {
                cur.next = addTwoNumbers(l1, new ListNode(plus));
            } else {
                cur.next = l1;
            }
        } else if (l2 != null) {
            if (plus != 0) {
                cur.next = addTwoNumbers(l2, new ListNode(plus));
            } else {
                cur.next = l2;
            }
        } else if (plus != 0) {
            cur.next = new ListNode(plus);
        }

        return head.next;
    }
    public static void main(String args[])
    {
        ListNode l1=new ListNode(2);
        l1.next=new ListNode(4);
        l1.next.next=new ListNode(3);

        ListNode r1=new ListNode(5);
        r1.next=new ListNode(6);
        r1.next.next=new ListNode(4);

        ListNode newnode=addTwoNumbers(l1,r1);

        while(newnode!=null)
        {
            System.out.println(newnode.val);
            newnode=newnode.next;
        }


    }
}

在声明Listnode时,竟然感觉有点吃力,忘了数据结构是怎么样的了,然后查了一下才解决,其实,用java声明单链表是很简单的,如下所示:

public class ListNode {
    int val;
    ListNode next;

    public ListNode(int x){
        val = x;
        next = null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值