[LeetCode]Add Two Numbers

题目描述

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. Add the twonumbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

将两个非负数字的链表对应节点相加得到新的链表,其中每个节点表示的值为单独的数字。

解题思路

通读此题,在理解上并不困难,只需要将相应节点数字相加即可。但是在具体编代码时应该考虑如下几种情况:

0)有链表为空

1)正常情况,有进位

2)L1和L2不等长,其实case0是此类的特例

3)最后一个点有进位


代码

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		//l1==null或l2==null或l1=l2==null情况
		if (l1 == null)
			return l2;
		if(l2==null)
			return l1;

		ListNode h1 = l1, h2 = l2;
		int lastVal = h1.val + h2.val;
		ListNode newHead = new ListNode(lastVal % 10);
		ListNode tailNode = newHead, tempNode = null;

		h1 = h1.next;
		h2 = h2.next;
		while (h1 != null || h2 != null) {
			//l1和l2不等长的情况
			if (h1 == null) {
				lastVal = h2.val + lastVal / 10;
			} else if (h2 == null) {
				lastVal = h1.val + lastVal / 10;
			} else {
				lastVal = h1.val + h2.val + lastVal / 10;
			}
			tempNode = new ListNode(lastVal % 10);
			tailNode.next = tempNode;
			tailNode = tempNode;

			if (h1 != null) {
				h1 = h1.next;
			}

			if (h2 != null) {
				h2 = h2.next;
			}

		}

		//考虑最后一个节点相加有进位的情况
		if (lastVal >= 10) {
			tempNode = new ListNode(1);
			tailNode.next = tempNode;
		}

		return newHead;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值