Search code examples
c++runtime-errorbuffer-overflow

This code gives me runtime error. How to fix this code?


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

this is a leetcode question and it start like this You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

int reverse(int n) {
  int reversedNumber = 0, remainder;

  while (n != 0) {
    remainder = n % 10;
    reversedNumber = reversedNumber * 10 + remainder;
    n /= 10;
  }

  return reversedNumber;

}
int converttoint(vector < int > array) {

  int number = 0;

  for (int i = 0; i < 3; i++) {
    number *= 10;
    number += array[i];
  }

  return number;

}
class Solution {
  public:
    ListNode * addTwoNumbers(ListNode * l1, ListNode * l2) {
      vector<int> vec, vec2;

      while (l1->next != NULL || l2->next != NULL) {
        if (l1->val != 0) {
          vec.insert(vec.begin(), l1->val);
          l1 = l1->next;
        }
        if (l2->val != 0) {
          vec2.insert(vec2.begin(), l2->val);
          l2 = l2->next;
        }

      }

      //adding the value
      int result = converttoint(vec) + converttoint(vec2);
      int reversedvalue = reverse(result);
      vector<int> otp;

      struct ListNode * r1;
      for (int i = to_string(reversedvalue).length(); i >= 0; i--) {
        otp.push_back(reversedvalue % 10);

        r1->val = reversedvalue % 10;
        r1 = r1->next;
        reversedvalue /= 10;
      }
      r1->next = NULL;

      return r1;
    }
}; 

Solution

  • In the converttoint function, I don't understand why you have:

    for (int i = 0; i < 3; i++) {
        number *= 10;
        number += array[i];
    }
    

    I think it needs to be:

    for (int i = 0; i < array.size(); i++) {
        number *= 10;
        number += array[i];
    }
    

    On a side note, you don't need all this vector stuff either (unless you're explicitly asked to do so). The list would be something like:

    1 --> 2 --> NULL
    3 --> 4 --> 5 --> NULL
    

    You can add it simply because the number is given in reverse! (take care of carry appropriately)

    4 --> 6 --> 5 --> NULL