×

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java.

Method 1

In this method two pointers are used, one of which advances quickly, and the other of which goes slowly. The fast pointer reaches the end of the list before the two-pointers do. Once the fast pointer has reached the end of the linked list, we check the location of the slow pointer, which moves one step at a time. the slow pointer is now at the middle node of the linked list.

Program for Finding middle node of a linked list using two pointer technique

MiddleNodeTwoPointer.java

// importing required packages
import java . util . * ;
import java . io . * ;
class Node 
{  
int n1 ;  
Node next;  
Node ( int n )  
{  
this . n1 = n ;    
this . next = null ;  
}  
}  
public class MiddleNodeTwoPointer  
{  
// find static method used to locate the middle element
public void find ( Node n )  
{  
if ( n == null )   
{   
return  ;  
}  
// declaring two pointers 
// one pointer is named slow pointer
Node slow_P  = n ;    
// Other pointer is named fast pointer
Node fast_p = n ;  
while  ( fast_p ! = null && fast_p . next != null )  
{   
fast_p  = fast_p . next . next ;  
slow_P  = slow_P . next ;  
}  
System . out . println ( " The middle node in  the linked list is: " + slow_P . n1 ) ;  
}  
// Main  method where execution of the program started 
public static void main ( String argvs [ ] )  
{  
// declaring head node of the linked list  
Node head = new Node ( 12 ) ;  
// adding nodes to the linked list 
Scanner sc = new Scanner ( System . in ) ;
System . out . println ( " Enter the element to be inserted " ) ;
int n = sc . nextInt ( ) ;
head . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next = new Node ( n ) ;   
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next . next . next = new Node ( n )  ;  
System . out . println ( " Enter the element to be inserted " ) ;
n = sc .nextInt ( ) ;
head . next . next . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " )    ;
n = sc . nextInt ( ) ;
head . next . next . next . next . next . next = new Node ( n ) ;  
MiddleNodeTwoPointer o1 = new MiddleNodeTwoPointer  ( ) ;  
o 1. find  ( head ) ;  
}  
}  

Output

Finding middle node of a linked list in Java

Method 2

In this method, we will start by determining the linked list's overall size. All of the connected list's nodes will now be pushed into the stack. The entire size is then divided by two, and we repeat the pop operation on the stack up to that number of times. Top   node present in the stack represents middle node.

Program for Finding middle node of a linked list using stacks

MiddleNode2.java

import java . util . * ;  
class Node  
{  
int n1;  
Node next ;  
Node ( int n)  
{   
this . n1 = n ;    
this . next  = null ;  
}  
}  
public class MiddleNode
{  
public int size ( Node h )  
{  
int size1 = 0;  
while ( h ! = null )  
{  
size1 = size1 + 1 ;  
h = h . next ;  
}  
return size1 ;  
}  
public void findNode ( Node n )  
{  
Stack < Node > stk = new Stack < Node > ( ) ;  
Node head = n ;   
while  ( head ! = null )  
{  
stk . push ( head ) ;  
head = head . next ;  
}  
int s = size ( n ) ;  
s = s / 2 ;  
while ( s ! = 0 )  
{  
stk . pop ( ) ;  
s = s - 1;  
}  
int val  = ( stk . peek ( ) ) . n1 ;  
System . out . println ( " The middle node of the linked list is : " + val ) ;  
}  
// main method where execution of the program starts  
public static void main ( String argvs [ ] )  
{  
// declaring head node of the linked list  
Node head = new Node ( 12 ) ;  
// adding nodes to the linked list 
Scanner sc = new Scanner ( System . in ) ;
System . out . println ( " Enter the element to be inserted " ) ;
int n = sc . nextInt ( ) ;
head . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next = new Node ( n) ;   
System . out.println (" Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next . next . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n=sc . nextInt ( )  ;
head . next . next . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( )  ; 
head . next . next . next . next . next . next = new Node ( n ) ;
// creating an object of the class StackExample1  
MiddleNode  O1 = new MiddleNode  ( ) ;  
// invoking the method findNode ( )  
O1 . findNode ( head ) ;  
}  
}  

Output

Finding middle node of a linked list in Java

Method 3

In this method, the middle node of the linked list will be located using a queue. We will start by determining the linked list's overall size. All of the connected list's nodes will now be pushed into the queue. The total size is then divided by 2, and whatever number results, we remove nodes from the queue up to that many times. Our response, the middle node, is the queue's top or peek node.

Program for Finding middle node of a linked list using Queues

// importing required packages
import java . util .*;  
// creating class for nodes
class Node  
{  
// value at node
int n1; 
// address of the next node
Node next ;  
// constructor for the class node 
Node ( int n )  
{  
this . n1 = n ;  
this. next = null ;  
}  
}  
public class QueueMiddle  
{  
public int size ( Node head )  
{    
int size1 = 0 ;   
while ( head ! = null )  
{  
size1 = size1 + 1 ;      
head = head . next  . ;  
}  
return size1 ;  
}  
public void find ( Node n )  
{  
Queue < Node > q = new LinkedList < Node > ( ) ;  
Node h =  n ;  
// pushing the node from the stack  
while ( h  ! = null )  
{  
q . add ( h ) ;  
h = h . next ;  
}  
// calling the method size ( )  to   find the size of the linked list  
int s = size(n);  
// dividing the size by 2  to find middle point
s = s / 2 ;  
while ( s ! = 0 )   
{  
q . remove ( ) ;  
s = s – 1 ;  
}  
// the value of the top node present in the stack   
int val = ( q . peek ( ) ) . n1 ;  
System . out . println ( " The middle node in  the given  linked list is : " + val ) ;  
}  
// main method  where execution of the program starts
public static void main ( String argvs [ ] )  
{  
// head node
Node head = new Node ( 43 ) ;  
Scanner sc = new Scanner ( System . in ) ;
System . out . println ( " Enter the element to be inserted " ) ;
int n = sc . nextInt ( ) ;
head . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n=sc . nextInt ( ) ;
head . next . next = new Node ( n ) ;  
System . out .  println ( " Enter the element to be inserted " ) ; 
n=sc . nextInt ( ) ;
head . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " ) ;
n=sc . nextInt ( ) ;
head . next . next . next . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n = sc . nextInt ( ) ;
head . next . next . next . next . next = new Node ( n ) ;
System . out . println ( " Enter the element to be inserted " ) ;
n=sc . nextInt ( ) ;
head . next . next . next . next . next . next = new Node ( n ) ;
QueueMiddle o1 = new QueueMiddle (  )  ;  
// calling  method find ( )  
o1 . find ( head ) ;  
}  
}  

Output

Finding middle node of a linked list in Java

Method 4

To locate the middle node of the linked list using this method, we will only utilise one pointer. We will start by determining the linked list's overall size. Next, we divide the total size by 2, and whichever number results, we shift the pointer to that many times, beginning at the head node. The middle node of the linked list is the node to which the pointer is now pointing.

Program for Finding middle node of a linked list using one pointer

import java.util.*;
class Node  
{  
int n1;  
Node next;  
Node(int n)  
{  
this.n1 = n;  
this.next = null;  
}  
}  
public class Main  
{  
public int size(Node head)  
{  
int size1 = 0;  
while(head != null)  
{  
size1 = size1 + 1;  
head = head.next;  
}  
return size1;  
}  
 public void findNode(Node n)  
{  
Node head = n;  
int s = size(n);  
s = s / 2;  
 while(s != 0)  
{  
  head = head.next;  
s = s - 1;  
}  
int val = head.n1;  
System.out.println("The middle node in the linked list is: " + val);  
 }  
public static void main(String argvs[])  
{  
Scanner sc=new Scanner(System.in);
// head node
Node head = new Node ( 43 ) ;  
// Scanner sc = new Scanner ( System . in ) ;
System . out . println ( " Enter the element to be inserted " ) ;
int n = sc . nextInt ( ) ;
head . next = new Node ( n ) ;  
System . out . println ( " Enter the element to be inserted " ) ;
n=sc . nextInt ( ) ;
head . next . next = new Node ( n ) ;  
System . out .  println ( " Enter the element to be inserted " ) ; 
n=sc . nextInt ( ) ;
head . next . next . next = new Node ( n ) ;
Main o1 = new Main();    
// invoking the method findNode()  
o1.findNode(head);  
}  
}  

Output

Finding middle node of a linked list in Java

Related Topics

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.