Java Program For Inserting Node In The Middle Of The Linked List
Last Updated :
10 Jul, 2022
Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.
Examples:
Input : list: 1->2->4->5
x = 3
Output : 1->2->3->4->5
Input : list: 5->10->4->32->16
x = 41
Output : 5->10->4->41->32->16
Method 1(Using length of the linked list):
Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node.
Java
// Java implementation to insert node
// at the middle of the linked list
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList
{
static Node head; // head of list
/* Node Class */
static class Node {
int data;
Node next;
// Constructor to create a new node
Node(int d) {
data = d;
next = null;
}
}
// function to insert node at the
// middle of the linked list
static void insertAtMid(int x)
{
// if list is empty
if (head == null)
head = new Node(x);
else {
// get a new node
Node newNode = new Node(x);
Node ptr = head;
int len = 0;
// calculate length of the linked list
//, i.e, the number of nodes
while (ptr != null) {
len++;
ptr = ptr.next;
}
// 'count' the number of nodes after which
// the new node is to be inserted
int count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = head;
// 'ptr' points to the node after which
// the new node is to be inserted
while (count-- > 1)
ptr = ptr.next;
// insert the 'newNode' and adjust
// the required links
newNode.next = ptr.next;
ptr.next = newNode;
}
}
// function to display the linked list
static void display()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
}
// Driver program to test above
public static void main (String[] args)
{
// Creating the list 1.2.4.5
head = null;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
System.out.println("Linked list before "+
"insertion: ");
display();
int x = 3;
insertAtMid(x);
System.out.println("
Linked list after"+
" insertion: ");
display();
}
}
// This article is contributed by Chhavi
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Space complexity: O(1) using constant space
Method 2(Using two pointers):
Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list.
Java
// Java implementation to insert node
// at the middle of the linked list
import java.util.*;
import java.lang.*;
import java.io.*;
class LinkedList
{
static Node head; // head of list
/* Node Class */
static class Node {
int data;
Node next;
// Constructor to create a new node
Node(int d) {
data = d;
next = null;
}
}
// function to insert node at the
// middle of the linked list
static void insertAtMid(int x)
{
// if list is empty
if (head == null)
head = new Node(x);
else {
// get a new node
Node newNode = new Node(x);
// assign values to the slow
// and fast pointers
Node slow = head;
Node fast = head.next;
while (fast != null && fast.next
!= null)
{
// move slow pointer to next node
slow = slow.next;
// move fast pointer two nodes
// at a time
fast = fast.next.next;
}
// insert the 'newNode' and adjust
// the required links
newNode.next = slow.next;
slow.next = newNode;
}
}
// function to display the linked list
static void display()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
}
// Driver program to test above
public static void main (String[] args)
{
// Creating the list 1.2.4.5
head = null;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
System.out.println("Linked list before"+
" insertion: ");
display();
int x = 3;
insertAtMid(x);
System.out.println("
Linked list after"+
" insertion: ");
display();
}
}
// This article is contributed by Chhavi
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Space complexity: O(n) where n is size of linked list
Please refer complete article on Insert node into the middle of the linked list for more details!
Similar Reads
Java Program to Insert a New Node at the Middle of the Circular Linked List Given a Circular Linked List, the task is to add a New Node at the Middle of the List. Let's consider the following Circular Linked List: List-Before-InsertionList-After-InsertionCreate a new node (New_node).Check for an empty list. If the list is empty then insert the node as head.For non-empty lis
3 min read
Java Program For Inserting A Node In A Linked List We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. Java // Linked List Class class LinkedList { // Head of list Node
7 min read
Java Program to Delete a Node From the Middle of the Circular Linked List In this article, we are going to learn to delete the middle node from the circular Linked List in java. The approach we are going to follow for this program is, first we calculate the number of nodes in the list and then divide the number of nodes by 2 to get the middle node of the list. Algorithm C
4 min read
Java Program to Insert a New Node at the Beginning of the Circular Linked List Circular linked list: A circular linked list is a sequence of elements in which every element points to its next element in the sequence and the last element has a link to the first element. That means a circular linked list is similar to the single linked list except that the last node points to th
4 min read
Java Program For Making Middle Node Head In A Linked List Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input: 1 2 3 4 5 Output: 3 1 2 4 5 Input: 1 2 3 4 5 6 Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves
3 min read
Java Program For Insertion Sort In A Singly Linked List We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
4 min read
Java Program For Finding The Middle Element Of A Given Linked List Given a Singly linked list, find the middle 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 of Finding Middle Element of Linked ListInput: 1->2->3->4->5 Output: 3Â Input: 1->2->3->4->5->
6 min read
Java Program To Delete Middle Of Linked List Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
4 min read
Java Program to Delete a Node From the Ending of the Circular Linked List In this article, we will learn about deleting a node from the ending of a circular linked list. Consider the linked list as shown below:Â Example:Input : 5->3->4->(head node)Output: 5->3->(head node)We will first initialize the list and add some data into it with the addNode() method a
3 min read
Java Program For Writing A Function To Get Nth Node In A Linked List Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2 Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before moving on to th
4 min read