diff --git a/Find Middle Of LinkedList b/Find Middle Of LinkedList index c90cd60..8bd2aaa 100644 --- a/Find Middle Of LinkedList +++ b/Find Middle Of LinkedList @@ -1,65 +1,41 @@ - import java.util.*; -// Node class represents a node in a linked list class Node { - // Data stored in the node - int data; - // Pointer to the next node in the list - Node next; + int data; + Node next; - // Constructor with both data - // and next node as parameters - Node(int data, Node next) { + Node(int data) { this.data = data; - this.next = next; } - // Constructor with only data as - // a parameter, sets next to null - Node(int data) { + Node(int data, Node next) { this.data = data; - this.next = null; + this.next = next; } } public class FindMiddleOfLinkedList { - + static Node findMiddle(Node head) { - // Initialize the slow pointer to the head. - Node slow = head; - - // Initialize the fast pointer to the head. - Node fast = head; + if (head == null) return null; - // Traverse the linked list using - // the Tortoise and Hare algorithm. - while (fast != null && fast.next != null && slow != null) { - // Move fast two steps. - fast = fast.next.next; - // Move slow one step. - slow = slow.next; + Node slow = head, fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; } - // Return the slow pointer, - // which is now at the middle node. - return slow; + return slow; } - public static void main(String[] args) { - // Creating a sample linked list: - Node head = new Node(1); - head.next = new Node(2); - head.next.next = new Node(3); - head.next.next.next = new Node(4); - head.next.next.next.next = new Node(5); + Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5))))); - // Find the middle node Node middleNode = findMiddle(head); - // Display the value of the middle node - System.out.println("The middle node value is: " + middleNode.data); + if (middleNode != null) + System.out.println("The middle node value is: " + middleNode.data); + else + System.out.println("The list is empty."); } } - -