Saturday 7 October 2017

Finding the middle Node of the Linked List using fast and slow method

Fast and slow pointers are very useful in LinkedList especially when traversal of the LinkedList is required several times.

Here is an implementation of fast and slow method for finding the middle of the LinkedList without traversing the whole array.

class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}

class LinkedList {
static Node head;

public static Node printMiddle(Node head) {
Node fast_ptr = head;
Node slw_ptr = head;
if(head != null) {
while(fast_ptr != null && fast_ptr.next != null) {
fast_ptr = fast_ptr.next.next;
slw_ptr = slw_ptr.next;
}
System.out.println("The middle element is: " + slw_ptr.data);
}
return slw_ptr;
}

public static void main(String[] args) {
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);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
head.next.next.next.next.next.next.next = new Node(8);
head.next.next.next.next.next.next.next.next = new Node(9);

printMiddle(head);
}


Please feel free to comment over for any suggestions / doubts.

No comments:

Post a Comment