How do you find the middle element of a linked list in one pass read more?

How to Find Middle Element of LinkedList in One Pass

Here is a complete Java program to find the middle node of Linked List in Java. Remember LinkedList class here is our custom class and don’t confuse this class with java.util.LinkedList is a popular Collection class in Java.

In this Java program, our class LinkedList represents a linked list data structure that contains a collection of the node and has a head and tail.

Each node contains data and addresses part. The main method of LinkedListTest class is used to simulate the problem, where we created Linked List and added few elements on it and then iterate over them to find the middle element of linked list in one pass in Java.

If you want to learn more about linked list data structure and different types of linked lists like a singly linked list, doubly linked list, circularly linked list et all then you can also check theAlgorithms and Data Structures - Part 1 and 2courses on Pluralsight. One of the better course to learn data structure and algorithms.



Btw, you would need a Pluralsight membership to access this course. If you are not a member, you can still access this course by using the 10-day free pass provided by Pluralsight to explorer its portal and online courses.




Java Program to Find the Middle Node of a Linked list in a Single-pass


import test.LinkedList.Node;

/**
* Java program to find middle element of linked list in one pass.
* In order to find middle element of a linked list
* we need to find the length first but since we can only
* traverse linked list one time, we will have to use two pointers
* one which we will increment on each iteration while

* other which will be incremented every second iteration.
* So when the first pointer will point to the end of a
* linked list, second will be pointing to the middle
* element of a linked list

*
* @author Javin Paul
*/

public class LinkedListTest {


public static void main[String args[]] {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList[];
LinkedList.Node head = linkedList.head[];
linkedList.add[ new LinkedList.Node["1"]];
linkedList.add[ new LinkedList.Node["2"]];
linkedList.add[ new LinkedList.Node["3"]];
linkedList.add[ new LinkedList.Node["4"]];

//finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;

while[current.next[] != null]{
length++;
if[length%2 ==0]{
middle = middle.next[];
}
current = current.next[];
}

if[length%2 == 1]{
middle = middle.next[];
}


System.out.println["length of LinkedList: " + length];
System.out.println["middle element of LinkedList : " + middle];

}

}

class LinkedList{
private Node head;
private Node tail;

public LinkedList[]{
this.head = new Node["head"];
tail = head;
}

public Node head[]{
return head;
}

public void add[Node node]{
tail.next = node;
tail = node;
}

public static class Node{
private Node next;
private String data;

public Node[String data]{
this.data = data;
}

public String data[] {
return data;
}

public void setData[String data] {
this.data = data;
}

public Node next[] {
return next;
}

public void setNext[Node next] {
this.next = next;
}

public String toString[]{
return this.data;
}
}
}

Output:
length of LinkedList: 4
the middle element of LinkedList: 2




That’s all on How to find the middle element of LinkedList in one pass. As I said this is a good interview question to separate programmers from non-programmers. Also, the technique mentioned here to find the middle node of LinkedList can be used to find the 3rd element from Last or nth element from last in a LinkedList as well.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Introduction to Algorithms by Thomas H. Corman
Grokking the Coding Interview: Patterns for Coding Questions


If you like this article and would like to try out a couple of more challenging programming exercise, then take a look at following programming questions from various Interviews :
  • How to check if LinkedList contains any cycle in Java? [solution]
  • How to search an element in an array in Java? [solution]
  • How to sort an array using bubble sort algorithm? [algorithm]
  • How to calculate Sum of Digits of a number in Java? [Solution]
  • Write a program to find first non repeated characters from String in Java? [program]
  • How to check if a number is binary in Java? [answer]
  • Write a program to check if a number is Prime or not? [solution]
  • How to prevent Deadlock in Java? [solution]
  • How to find the largest prime factor of a number in Java? [solution]
  • How to calculate a factorial using recursion in Java? [algorithm]
  • How to declare and initialize a two-dimensional array in Java? [solution]
  • Write a method to count occurrences of a character in String? [Solution]
  • How to check if a number is Armstrong number or not? [solution]
  • Write a Program remove duplicates from an array without using Collection API? [program]
  • How to reverse String in Java without using API methods? [Solution]
  • Write a method to remove duplicates from ArrayList in Java? [Solution]
  • Write a program to check if a number isa Palindromeor not? [program]
  • Write a program to check if the Array contains a duplicate number or not? [Solution]
  • How to find the Fibonacci sequence up to a given number? [solution]
  • Write a program to find a missing number in a sorted array? [algorithm]
  • 10 Points about Array in Java? [must-know facts]
  • How to find the top two maximum on integer array in Java? [solution]
  • Write a method to check if two String are Anagram of each other? [method]
  • How to find the largest and smallest number in an array? [solution]
  • Write a function to find the middle element of the linked list in one pass? [solution]
  • How to solve the Producer-Consumer Problem in Java. [solution]
  • Write a Program to Check if a number is Power of Two or not? [program]

Thanks for reading this coding interview question so far. If you like this String interview question then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check this list of Free Data Structure and Algorithms Courses for Programmers.

Middle of the Linked List

Difficulty: Easy

Understanding the Problem

Problem Description

Given a non-empty, singly linked list with head node head, write a program to return a middle node of the linked list. If there are even nodes, then there would be two middle nodes, we need to print the second middle element.

Example 1

Input: 11->2->13->44->5 Output: 13 Explanation: The middle element of the linked list is 13.

Example 2

Input: 10->2->34->24->15->60 Output: 24 Explanation: As there are even number of nodes, return 24 as it is the second node among two middle elements.

Solutions

  1. Two-Pass: Find the length of the linked list and return the [length/2]th node.
  2. One-Pass: Use two pointers, the 2nd pointer should traverse twice as fast at the first.

Before moving forward with the question, you must understand the properties of a linked list.

You can try this problem here.

1. Two-Pass

The question demands to find the middle of a singly linked list. We can simply find the total length of the linked list, in this way we can identify which node falls in the middle. To find the middle node, we can traverse again until we reach [length/2]th node.

Solution Steps

Pseudo Code

int middleNode[ListNode head] { int l=0 ListNode p = head while [p != null] { p = p.next l = l + 1 } p = head int c = 0 while [c < l/2] { p = p.next c = c + 1 } return p.data }

Complexity Analysis

Time Complexity: O[n]

Space Complexity: O[1]

Critical Ideas To Think

2. One-Pass

Another way to solve this problem is to use a little trick. Instead of traversing twice, we can create two-pointers say slow_ptr and fast_ptr.We can make the fast_ptr twice as fast as slow_ptr. So, When the fast_ptr will reach to the end of the linked list, slow_ptr would still be at the middle, thereby pointing to the mid of the linked list.

Solutions Steps

Pseudo Code

int middleNode[ListNode head] { ListNode slow = head ListNode fast = head while [fast != null and fast.next != null] { slow = slow.next fast = fast.next.next } return slow.data }

Complexity Analysis

Time Complexity: O[n]

Space Complexity: O[1]

Critical Ideas To Think

Comparison Of Different Approaches

Suggested Problems To Solve

Happy coding!

Enjoy Algorithms.

1. Overview

In this tutorial, we're going to explain how to find the middle element of a linked list in Java.

We'll introduce the main problems in the next sections, and we'll show different approaches to solving them.

Java Program to Get the middle element of LinkedList in a single iteration

In this example, we will learn to get the middle element of the linked list in a single iteration in Java.

To understand this example, make sure you first visit the following tutorials,

  • Java LinkedList Class
  • LinkedList Data Structure

How to Find Middle Element of Linked List in Java in Single Pass

Posted by: Javin Paul in Core Java March 26th, 2019 0

Howdo you find the middle element of LinkedList in one pass is a programming question often asked Java and non-Java programmers in telephonic Interview. This question is similar to checking palindrome or
calculating the factorial, where Interviewer sometimes also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure i.e. In the case of singly LinkedList, each node of Linked List contains data and pointer, which is the address of next Linked List and the last element of Singly Linked List points towards the null. Since in order to find middle element of Linked List you need to find the length of linked list, which is counting elements till end i.e. until you find the last element of Linked List.

What makes this data structure Interview question interesting is that you need to find the middle element of inkedList
in one pass and you don’t know the length of LinkedList.

This is where candidates logical ability puts into the test, whether he is familiar with space and time trade-off or not etc.

As if you think carefully you can solve this problem by using two pointers as mentioned in my last post onHow to find the length of the Singly Linked List in Java.

By using two pointers, incrementing one at each iteration and other at every second iteration. When the first pointer will point at end of Linked List, the second pointer will be pointing at a middle node of Linked List.

In fact, this two pointer approach can solve multiple similar problems like
how to find the third node from last in a Linked List in one Iteration or how to find an Nth element from last in a Linked List. In this Java programming tutorial, we will see a Java program which finds the middle element of Linked List in one Iteration.

Video liên quan

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề