e-olymp
favorite We need a little bit of your help to keep things running, click on this banner to learn more
Competitions

class LinkedList

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) {}
};

Implement a function hasCycle that returns 1 if linked list contains a cycle and 0 otherwise.

// Java
int hasCycle(ListNode head)
// 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