Skip to content
Advertisement

Leetcode #2, getting detected a cycle error

I was trying to solve leetcode#2, 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. https://leetcode.com/problems/add-two-numbers/ I am getting Error: cycle detected only for additon of single digit numbers. What am I doing wrong?

JavaScript

Advertisement

Answer

In your code snippet there are lines:

JavaScript

It makes the LC cycle detection algorithm complain.

If you consider the first run of the while loop, you can find that mover points to the same object to which newnode does.

In other words, object ListNode newnode = new ListNode(); ends up with a cyclic edge to itself after mover.next = newnode;.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement