0

I am looking at the following code from programcreek.com on finding cycles in linked list and wondering how variable 'head' of type ListNode is declared here by passing it as an argument to the boolean method. Is there a data type ListNode in Java. I can't seem to find it in the documentation. Secondly, how do we analyze time and space complexity for this.

public class Solution {
 public boolean hasCycle(ListNode head) {
 ListNode fast = head;
 ListNode slow = head;
 if(head == null)
 return false;
 if(head.next == null)
 return false;
 while(fast != null && fast.next != null){
 slow = slow.next;
 fast = fast.next.next;
 if(slow == fast)
 return true;
 }
 return false;
 }
}
Neithrik
2,0763 gold badges21 silver badges33 bronze badges
asked Apr 13, 2015 at 1:57
1
  • stackoverflow.com/a/2663147/1897935 two people run around a circle at different speeds . both have to met at some point of time . (IF it has 2 directions then u can go from both way and find cycle BUT u just have one direction ) Commented Apr 13, 2015 at 2:46

2 Answers 2

0

In this function boolean is the return type of the funtion hasCycle(). The input of this function is object of Class ListNode for which you need to find cycle if exists. This function works fine. I don't think Java has a class named ListNode. You can find the time complexity here

answered Apr 13, 2015 at 2:40
1
  • Since input of this function is object of Class ListNode should the class ListNode be declared separately for the code to work ? Commented Apr 13, 2015 at 12:13
0

ListNode classis not defined in java and it has to be defined separately.Here is an example of how it can be defined

public class linkedlistcycle {
 class ListNode {
 int val;
 ListNode next;
 ListNode(int x) {
 val = x;
 next = null;
 }
 }
 public boolean hasCycle(ListNode head){
 ListNode a = head ;
 ListNode b = head ;
 if ((head == null) || (head.next==null))
 { return false;}
 while ((head != null) | (head.next != null))
 {
 a = a.next ;
 b = b.next.next;
 if(a == b)
 return true;
 } 
 return false ;
 }
 }
answered Apr 13, 2015 at 12:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.