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
Solution:
1. transfer node's value to each digit then combine to a long integer.
2. use math method to calculate.
3. transfer the result to digits and append to each node.
需要注意的是:
1. 计算数字的类型需要是long,否则无法通过大数据检测。
2. 在将数字转换并存储到Node中时,使用了append方法,这样有两次循环,运行时间似乎是O(n*n)?
这道题还有two pointers的解法,不过感觉我这种解法比较直观。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
long v1 = nodeToInt(l1);
long v2 = nodeToInt(l2);
long sum = v1 + v2;
return intToNode(sum);
}
public long nodeToInt(ListNode n){
Stack<Integer> st = new Stack<Integer>();
while(n!=null){
st.push(n.val);
n = n.next;
}
long result = 0;
while(!st.isEmpty()){
result = result*10 + st.pop();
}
return result;
}
public ListNode intToNode(long number){
String s = number + "";
int len = s.length();
int h = Character.getNumericValue(s.charAt(len-1));
ListNode head = new ListNode(h);
for(int i=len-2; i>=0; i--){
ListNode n = head;
ListNode end = new ListNode(Character.getNumericValue(s.charAt(i)));
while(n.next != null){
n = n.next;
}
n.next = end;
}//append node here!!!
return head;
}
}
2015-03-14更新:
Python Solution: 链表的遍历,创建一个新的链表来储存计算好的值,注意链表l1和链表l2的长度区别,以及最后时段的进位。
Running Time: O(n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
dummy = ListNode(-1)
p = dummy
carry = 0
while l1 and l2:
temp = l1.val + l2.val + carry
node_value = temp % 10
carry = temp / 10
p.next = ListNode(node_value)
p = p.next
l1 = l1.next
l2 = l2.next
while l1:
temp = l1.val + carry
node_value = temp % 10
carry = temp / 10
p.next = ListNode(node_value)
p = p.next
l1 = l1.next
while l2:
temp = l2.val + carry
node_value = temp % 10
carry = temp / 10
p.next = ListNode(node_value)
p = p.next
l2 = l2.next
if carry > 0:
p.next = ListNode(carry)
return dummy.next