[LeetCode]Add Two Numbers

来源:互联网 发布:阿里云服务器架设vpn 编辑:程序博客网 时间:2024/05/19 11:34

题目描述

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;}


0 0