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
Function hasCycle returns 0 because this linked list does not contain a cycle.
Function hasCycle returns 1 because this linked list contains a cycle.