Kumar-laxmi / Algorithms

A Repository for algorithms in C, C++, Python and Java
Apache License 2.0
315 stars 365 forks source link

Detection of cycle in linked list in C, Java & Python #1403

Closed Kumar-laxmi closed 4 months ago

Kumar-laxmi commented 1 year ago

Is your feature request related to a problem? Please describe. Given a linked list, check if the linked list has a loop (cycle) or not. The below diagram shows a linked list with a loop. image

Describe the solution you'd like Follow the steps below to solve the problem:

Additional context image

tarunvyshnav777 commented 1 year ago

@Kumar-laxmi I can do this

vedang2003 commented 1 year ago

@Kumar-laxmi Please assign me this issue for SSOC'23. This shall be my first PR for SSOC

Kumar-laxmi commented 1 year ago

Assigned! @vedang2003 : C, Java & Python

Kumar-laxmi commented 1 year ago

@vedang2003 What is your status on this issue?

vedang2003 commented 1 year ago

Sorry for the delay I'll push the code today itself.

vedang2003 commented 1 year ago

Please check the PR.

NupurHardiya commented 1 year ago

Hello @Kumar-laxmi Please assign me this issue for SSOC'23. my approach will be :-

  1. Create a hash table to store the addresses of all the nodes in the linked list.
  2. Start traversing the linked list, and for each node, check if the node's address is already in the hash table.
  3. If the node's address is already in the hash table, then the linked list contains a loop.
  4. Otherwise, the node's address is added to the hash table, and the traversal continues.
  5. The code returns True if the linked list contains a loop, and False otherwise.

Here is an example of how the approach works:

Let's say we have the following linked list:

1 -> 2 -> 3 -> 4 -> 5 -> 1

The hash table will start out empty.

When we traverse the linked list, we will first add the node with the address 1 to the hash table.

Then, we will add the node with the address 2 to the hash table.

Then, we will add the node with the address 3 to the hash table.

Then, we will add the node with the address 4 to the hash table.

Finally, we will add the node with the address 5 to the hash table.

At this point, the hash table will contain all the nodes in the linked list.

When we try to add the node with the address 1 to the hash table again, we will find that the address is already in the hash table.

This means that the linked list contains a loop.

The code will return True to indicate that the linked list contains a loop.

Kumar-laxmi commented 1 year ago

Assigned! @NupurHardiya : C, Java & Python

github-actions[bot] commented 5 months ago

Stale issue message