Advertisement
Guest User

Untitled

a guest
May 24th, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. # solution
  2. # use one extra linked list to store the sum
  3. # traverse two original linked list to find the sum for each digit
  4. # pass the carry one forward
  5. # O(max(m, n)) in time, O(max(m, n)) in space
  6.  
  7. def solution(L1, L2):
  8. p1 = L1
  9. p2 = L2
  10. carry = 0
  11. sumNode = Node() # new linked list to store the sum
  12. res = sumNode
  13. while (p1 != None) or (p2 != None) or (carry != 0):
  14. tmpSum = carry
  15. if p1 != None:
  16. tmpSum += p1.value
  17. p1 = p1.next
  18. if p2 != None:
  19. tmpSum += p2.value
  20. p2 = p2.next
  21. sumNode.value = tmpSum % 10
  22. carry = tmpSum / 10
  23. sumNode = sumNode.next
  24. return res
  25.  
  26. # for forward order linked list, we could reverse the linked list
  27. # and add using the above method then reverse the result again
  28. # O(max(m, n)) in time, O(max(m, n)) in space
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement