Friday, November 28, 2014

Middle Element of Linked List

Approach

If we do not know the size of the linked list prior to finding the middle element, then our approach would be to use two pointers to traverse the list.
One pointer, the fast pointer, would move twice as fast as the the other pointer.  So if the slow pointer traverses one node per iterations, the fast pointer would traverse two nodes in the same time.
When the fast pointer reached the end of the list, the slow pointer would be in the middle.
This allows us to find the middle element in a running time of O(n).

      public Node<Type> printMiddle(Node<Type> head) {  
           Node<Type> slowPointer = head;  
           Node<Type> fastPointer = head;  
           while (fastPointer != null && fastPointer.next != null) {  
                slowPointer = slowPointer.next;  
                fastPointer = fastPointer.next.next;  
           }  
           System.out.println(slowPointer.data);  
           return slowPointer;  
      }  

No comments:

Post a Comment