Advertisement
Guest User

Untitled

a guest
May 20th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9.  
  10. #include <string>
  11.  
  12. class Solution {
  13. public:
  14. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  15. ListNode* sum = new ListNode(0);
  16. int overflow = 0;
  17. ListNode* init = sum;
  18. while(l1 != NULL && l2 != NULL){
  19. overflow = 0;
  20. sum->val = sum->val + l1->val + l2->val;
  21. if(l1->val + l2->val > 9){
  22. overflow = sum->val/10;
  23. sum->val = sum->val%10;
  24. }
  25. if(l1->next != NULL && l2->next != NULL){
  26. sum->next = new ListNode(overflow);
  27. }else{
  28. sum->next = new ListNode(0);
  29. }
  30.  
  31. sum = sum->next;
  32. l1 = l1->next;
  33. l2 = l2->next;
  34. }
  35.  
  36. if(overflow != 0){
  37. if(l1 == NULL && l2 != NULL){
  38. sum = l2;
  39. o_f(l2,overflow);
  40. }else if(l1 != NULL && l2 == NULL){
  41. sum = l1;
  42. o_f(l1,overflow);
  43. }else{
  44. sum = new ListNode(overflow);
  45. }
  46. }
  47.  
  48. return init;
  49. }
  50.  
  51. void o_f(ListNode* &L, int overflow){
  52. int temp = L->val;
  53. L->val = (L->val + overflow)%10;
  54. if(temp + overflow > 9){
  55. if(L->next != NULL){
  56. o_f(L->next, (temp + overflow)/10);
  57. }else{
  58. L->next = new ListNode((temp + overflow)/10);
  59. }
  60. }else{
  61. L = new ListNode(overflow);
  62. }
  63. }
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement