算法分析:
分别将两个链表存入栈中,然后将两个栈中的元素依次同时弹出,设置一个进位标记carry,两个元素和进位carry相加得到结果value,更新carry值,更新value值保证其小于10,采用头插法插入链表中。当2个栈中的一个为空时,则退出循环。然后继续插入栈不为空的元素节点,直到该栈为空。最后检查进位carry值,若carry不为零,则将carry插入链表中。时间复杂度O(n),空间复杂度O(n)。
参考代码
//leetcode 445. Add Two Numbers II
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<Integer> input1 = new Stack<Integer>();
Stack<Integer> input2 = new Stack<Integer>();
while(l1!=null){
input1.push(l1.val);
l1 = l1.next;
}
while(l2!=null){
input2.push(l2.val);
l2 = l2.next;
}
int carry = 0;
ListNode head = null;
while(!input1.empty()&&!input2.empty()){
int value = input1.pop()+input2.pop()+carry;
carry = value/10;
value = value%10;
ListNode node = new ListNode(value);
if(head==null){
head = node;
}else{
node.next = head;
head = node;
}
}
while(!input1.empty()){
int value = input1.pop()+carry;
carry = value/10;
value = value%10;
ListNode node = new ListNode(value);
node.next = head;
head = node;
}
while(!input2.empty()){
int value = input2.pop()+carry;
carry = value/10;
value = value%10;
ListNode node = new ListNode(value);
node.next = head;
head = node;
}
if(carry!=0){
ListNode node = new ListNode(carry);
node.next = head;
head = node;
}
return head;
}