How will you find the middle of the Linked List?
💻 coding

How will you find the middle of the Linked List?

2 min read 306 words
2 min read
ShareWhatsAppPost on X
  • 1To find the middle of a linked list, one approach involves calculating the length in two passes with O(n) time complexity.
  • 2Using two pointers, a slow pointer and a fast pointer, allows finding the middle in just one iteration.
  • 3The Java implementation demonstrates how to traverse the linked list and return the middle element efficiently.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To find the middle of a linked list, one approach involves calculating the length in two passes with O(n) time complexity."

How will you find the middle of the Linked List?

To find the middle of a linked list we can use many approaches. let's discuss our first approach having O(n) time complexity with 2 passes.

We will be calculating the length n of the linked list in the first iteration and in second iteration we will be traversing to n/2 length to get the middle of the linked list.

Can we do it in just 1 iteration?

Yes, we can use two pointers, 1 slow pointer and 1 fast pointer. we will be moving fast pointer two steps per iteration while slow pointer will move only one step per iteration. So when the fast pointer will reach the end of the linked list then the slow pointer will be at the middle of the linked list.

Java implementation of the above solution is as below:

package askgif.linkedlist;

import java.util.Stack;

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

public class LinkedListNode {

	public static void main(String[] args) {
		
 ListNode node1 = new ListNode(1);
 ListNode node2 = new ListNode(2);
 ListNode node3 = new ListNode(3);
 ListNode node4 = new ListNode(4);
 ListNode node5 = new ListNode(5);
 ListNode node6 = new ListNode(6);
 ListNode node7 = new ListNode(7);
 ListNode node8 = new ListNode(8);
 ListNode node9 = new ListNode(9);
 ListNode node10 = new ListNode(10);
 ListNode node11 = new ListNode(11);
 
 node1.next = node2;
 node2.next = node3;
 node3.next = node4;
 node4.next = node5;
 node5.next = node6;
 node6.next = node7;
 node7.next = node8;
 node8.next = node9;
 node9.next = node10;
 node10.next = node11;
 node11.next = null;
 
		System.out.println(GetMiddleElement( node1));
		

	}

	private static int GetMiddleElement(ListNode node1) {
		
		ListNode slowPtr = node1;
		ListNode fastPtr = node1;
		
		while(fastPtr != null && fastPtr.next != null) {
			slowPtr = slowPtr.next;
			fastPtr = fastPtr.next.next;
		}
		
		return slowPtr.data;
	}

}
output:

6

The time complexity of the above solution is O(n) and the space complexity is also O(n).

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 7 August 2018 · 2 min read · 306 words

Part of AskGif Blog · coding

You might also like