Detect Loop in Linked List

How to detect loop in linked list.

Given a linked list, determine if it has a cycle or loop in it.

For example:

In the below example, the last node (whose value is 9) points to node whose value is 5. The last node of a linked list does not points to a null. It has a cycle.

Detect a loop in a linked list

Detect loop in a linked list

Find Middle Element of a Linked List – Java Code

In this tutorial, Let’s discuss how to find middle element of a linked list in a single traversal.

Given a singly linked list, write a code to find middle element in a linked list.

For example: Given a linked list, the middle element in this linked list is 8.

15 -> 9 -> 8 -> 5 -> 6 -> NULL

This type of questions are generally asked in an interviews.

There are multiple approaches to solve this problem. In this tutorial, I am going to discuss two approaches through which we can find the middle element of a singly linked list in one pass.

I have also added video tutorial at the end of this post.

Programming video tutorials

Program to Delete a Linked List

Write a program to delete a linked list. Given a linked list, we have to write a code to delete a linked list.

To delete a complete linked list, traverse all the nodes of a linked list and delete one by one.

Print Middle Element of a Linked List

How to Delete a Linked List

To delete a node one by one maintain two pointers.  The first pointer points to head and the second pointer keeps the reference to next node. So when a node is free, you can assign the reference of next node using the second pointer.