eolymp
bolt
Try our new interface for solving problems
Problems

LinkedList Cycle

LinkedList Cycle

Given a linked list. Does it contain a cycle?

Definition of a single linked list:

// Java
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {
    val = x;
    next = null;
  }
}
// C++
class ListNode
{
public:
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};
// C
struct class ListNode
{
  int val;
  struct ListNode *next;
};

Implement a function hasCycle that returns 1 if linked list contains a cycle and 0 otherwise. It is forbidden to change the values of the list elements.

// Java
int hasCycle(ListNode head)
// C, C++
int hasCycle(ListNode *head)

Example

prb9898.gif

Function hasCycle returns 0 because this linked list does not contain a cycle.

prb10042_1.gif

Function hasCycle returns 1 because this linked list contains a cycle.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev