×

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

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.