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 two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
【算法思路】
采用合并的思想,计算每一位和进位的和。类似于合并链表吧。
【复杂度】
时间 :O(n) 遍历最长的那个链表
空间:O(1)
PS: 实现中注意维护进位,陷阱的话记住最后还要判一下有没有进位,如果有再生成一位。
这道题还是有一些扩展的,比如这个其实是BigInteger的相加,数据结果不一定要用链表,也可以是数组,面试中可能两种都会问而且实现。
然后接下来可以考一些OO设计的东西,比如说如果这是一个类应该怎么实现,也就是把数组或者链表作为成为成员变量,再把这些操作作为成员函数,进一步的问题可能是如何设计constructor,这个问题要对内置类型熟悉,比如int, long的constructor, 类似于BigInteger(int num), BigInteger(int long).
总体来说问题还是比较简单,但是这种问题不能出错,所以还是要谨慎对待。
【CODE】
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list = null;
int tmpVal = 0;
int tmpCarry = 0;
int tmpAns = 0;
if( (l1 == null) || (l2 == null) )
{
if(l1 != null)
list = l1;
else if(l2 != null)
list = l2;
return list;
}
tmpAns = l1.val + l2.val;
tmpVal = tmpAns % 10;
tmpCarry = tmpAns / 10;
list = new ListNode(tmpVal);
ListNode list1 = l1.next;
ListNode list2 = l2.next;
ListNode listHead = list;
while( (list1 != null) && (list2 != null) )
{
tmpAns = list1.val + list2.val + tmpCarry;
tmpVal = tmpAns % 10 ;
tmpCarry = tmpAns / 10;
ListNode tmpNode = new ListNode(tmpVal);
list.next = tmpNode;
list = list.next;
list1 = list1.next;
list2 = list2.next;
}
while(list1 != null)
{
tmpAns = list1.val + tmpCarry;
tmpVal = tmpAns % 10 ;
tmpCarry = tmpAns / 10;
ListNode tmpNode = new ListNode(tmpVal);
list.next = tmpNode;
list = list.next;
list1 = list1.next;
}
while(list2 != null)
{
tmpAns = list2.val + tmpCarry;
tmpVal = tmpAns % 10 ;
tmpCarry = tmpAns / 10;
ListNode tmpNode = new ListNode(tmpVal);
list.next = tmpNode;
list = list.next;
list2 = list2.next;
}
if(tmpCarry != 0)
{
ListNode tmpNode = new ListNode(tmpCarry);
list.next = tmpNode;
}
return listHead;
}
}