Question

Write a C# function bool HasCycle(Node head) that detects a cycle in a singly linked list....

Write a C# function bool HasCycle(Node head) that detects a cycle in a singly linked list.
It must return a boolean true if the list contains a cycle, or false otherwise. HasCycle
has a reference to a Node object, that points to the head of a linked list, as parameter.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

TO detect Loop in linked list we can this algorithm

Floyd’s Cycle-Finding Algorithm:

  • Traverse linked list using two pointers.
  • Move one pointer( p_slow )by one and another pointer(p_fast) by two.
  • If these pointers meet at the same node then there is a loop.
  • Else If pointers do not meet then linked list doesn’t have a loop

So Now try to code is in C#

Function is boolHasCycle( Node Head) takes head of the linked list as argument  

This function will return true if cycle is detected else false

Code is

bool HasCycle(Node head)
   {
       Node p_slow = head, p_fast = head;
       while (p_slow != null && p_fast != null &&
                               p_fast.next != null)
       {

// increment p_slow by one
           p_slow = p_slow.next;

// increment p_fast by two
           p_fast = p_fast.next.next;

// when they are equal or pointing to same node that means cycle is detected
           if (p_slow == p_fast)
           {
               return true;
           }
       }
       return false;
   }

Full Code for Complete Implementation of above function

using System;

public class LinkedList
{
   Node head; // head of list

   /* Linked list Node*/
   public class Node
   {
       public int data;
       public Node next;
       public Node(int d)
       {
           data = d;
           next = null;
       }
   }

   /* This function will Inserts a new Node at beginning of the list. */
   public void push(int new_data)
   {
       /* 1 & 2: Allocate the memory to Node &
               Put in the data*/
       Node new_node = new Node(new_data);

       // connect new node with head
       new_node.next = head;

       //Make Head to point to new node
  
       head = new_node;
   }
// This function is used to detect cycle in linked list
bool HasCycle(Node head)
   {
       Node p_slow = head, p_fast = head;
       while (p_slow != null && p_fast != null &&
                               p_fast.next != null)
       {
           p_slow = p_slow.next;
           p_fast = p_fast.next.next;
           if (p_slow == p_fast)
           {
          
               return true;
           }
       }
       return false;
   }

   public static void Main(String []args)
   {
       LinkedList llist = new LinkedList();
       bool found;

       llist.push(20);
       llist.push(4);
       llist.push(15);
       llist.push(10);

       /*Delibrately creating a loop in the list for testing */
      llist.head.next.next.next.next = llist.head;

       found=llist.HasCycle(llist.head);
       if(found)
       Console.WriteLine("Found loop in Linked List");
       else
       Console.WriteLine("No loop is found in Linked List");
      
   }
}

Output is

Found loop in Linked List

Input Code Screenshot

{ { { } } 1 using System; 2 3 public class LinkedList 4 5 Node head; // head of list 6 7 /* Linked list Node*/ 8 public classnew_node.next = head; //Make Head to point to new node head = new_node; } bool HasCycle(Node head) { Node p_slow = head, p_fa40 41 p_slow = p_slow.next; p_fast.next.next; if (p_slow == p_fast) p_fast 42 { 43 44 45 return true; 46 } } return false; }

So this is how we can check cycle in linked list using C#

If u like the answer then upvote it and have any doubt comment it

Add a comment
Know the answer?
Add Answer to:
Write a C# function bool HasCycle(Node head) that detects a cycle in a singly linked list....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • Extend Linked List in C // Exercise 5 /* Parameter head points to the first node in a linked list, or is * NULL if the l...

    Extend Linked List in C // Exercise 5 /* Parameter head points to the first node in a linked list, or is * NULL if the list is empty. * * Parameter other points to the first node in a linked list, or is * NULL if the list is empty. * * Extend the linked list pointed to by head so that it contains * copies of the values stored in the linked list pointed to by other. *...

  • Answer all questions 1- in circular singly linked list, previous pointer of the first node points...

    Answer all questions 1- in circular singly linked list, previous pointer of the first node points to which node A. First node B. Itself C. null D. Last node 2- Which of the following is NOT an applications of linked lists? A. Implementation of stacks and queues B. Dynamic memory allocation C. Manipulation of polynomials D. Keeping people at home during epidemics like corona virus 3- In a circular singly linked list? A. Components are all linked together in some...

  • Question 13 (6 points) Assume the singly linked list is defined as a head reference variable...

    Question 13 (6 points) Assume the singly linked list is defined as a head reference variable refers to the first node and a size reference variable refers to the number of nodes (similar like your L.AB4). Provide a method named count that used to count and return the occurrences of the head item (item stored at the head node) in the list. If the list is empty, return - 1. provide the appropriate method signature and implementation. Format BIU In...

  • Arrays, Lists, Stacks and Queues: 1) Write C++ code to reverse a singly-linked list L using...

    Arrays, Lists, Stacks and Queues: 1) Write C++ code to reverse a singly-linked list L using only a constant amount of additional storage and no recursion. Assume the list object has a head pointer _head and consists of Node objects; a Node object has a pointer Node* _next

  • 1)Given a singly linked list contains four nodes and simply show as 4->3->2->1, where the head...

    1)Given a singly linked list contains four nodes and simply show as 4->3->2->1, where the head reference refers to the first node contains an Integer with value 4. If Node curr = head; curr= curr.next; are applied to this list, what is the number you can find in the first node? 2) Given a singly linked list contains 6 nodes, which is simply shown as 1->2->3->4->5->6. Assume head refers to the first node (contains 1) on the list. How many...

  • Given the following linked list structure called node: struct node { int val; struct node *...

    Given the following linked list structure called node: struct node { int val; struct node * ptrNext; }; Assume we have a single list created from this structure with a head pointer called ptrFirst which is declared in the global scope. a. Write a complete C function called CountEven to count all the even values in this singly linked list of arbitrary number of nodes using an iterative (non-recursive) approach. The function takes as parameter the pointer to the starting...

  • Consider a singly linked list. What is true about the last node in the data structure?

    Question 14 Consider a singly linked list. What is true about the last node in the data structure? The node cannot store data values. The node points to the head node. The node points to null. The node points to head. Question 15 When defining an interface, you cannot implement another interface. you may not include more than one method signature. you must provide the body of at least one method. you must provide signatures for each method Question 16 Generics are allowed in the class definition header but not in a method definition...

  • Write a Python function to implement the quick sort algorithm over a singly linked list. The...

    Write a Python function to implement the quick sort algorithm over a singly linked list. The input of your function should be a reference pointing to the first node of a linked list, and the output of your function should also be a reference to the first node of a linked list, in which the data have been sorted into the ascending order. (You may use the LinkedQueue class we introduced in the lecture directly in your program.)

  • C++ program, inventory.cpp implementation Mostly need the int load(istream&) function. Implementation: You are supp...

    C++ program, inventory.cpp implementation Mostly need the int load(istream&) function. Implementation: You are supposed to write three classes, called Item, Node and Inventory respectively Item is a plain data class with item id, name, price and quantity information accompanied by getters and setters Node is a plain linked list node class with Item pointer and next pointer (with getters/setters) Inventory is an inventory database class that provides basic linked list operations, delete load from file / formatted print functionalities. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT