Java Program For Inserting A Node After The N-th Node From The End
Last Updated :
14 Aug, 2022
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n.
Examples:
Input : list: 1->3->4->5
n = 4, x = 2
Output : 1->2->3->4->5
4th node from the end is 1 and
insertion has been done after this node.
Input : list: 10->8->3->12->5->18
n = 2, x = 11
Output : 10->8->3->12->5->11->18
Method 1 (Using length of the list):
Find the length of the linked list, i.e, the number of nodes in the list. Let it be len. Now traverse the list from the 1st node upto the (len-n+1)th node from the beginning and insert the new node after this node. This method requires two traversals of the list.
Java
// Java implementation to insert a node after
// the n-th node from the end
class GfG
{
// structure of a node
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after the
// nth node from the end
static void insertAfterNthNode(Node head, int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
Node ptr = head;
int len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != null)
{
len++;
ptr = ptr.next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr.next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = ptr.next;
ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
System.out.print("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
System.out.println();
System.out.print("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by prerna saini
Output:
Original Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1)
Method 2 (Single traversal):
This method uses two pointers, one is slow_ptr and the other is fast_ptr. First move the fast_ptr up to the nth node from the beginning. Make the slow_ptr point to the 1st node of the list. Now, simultaneously move both the pointers until fast_ptr points to the last node. At this point the slow_ptr will be pointing to the nth node from the end. Insert the new node after this node. This method requires single traversal of the list.
Java
// Java implementation to
// insert a node after the
// nth node from the end
class GfG
{
// structure of a node
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after
// the nth node from the end
static void insertAfterNthNode(Node head,
int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
// Initializing the slow
// and fast pointers
Node slow_ptr = head;
Node fast_ptr = head;
// move 'fast_ptr' to point to the
// nth node from the beginning
for (int i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr.next;
// iterate until 'fast_ptr' points
// to the last node
while (fast_ptr.next != null)
{
// move both the pointers to the
// respective next nodes
slow_ptr = slow_ptr.next;
fast_ptr = fast_ptr.next;
}
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = slow_ptr.next;
slow_ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
System.out.println("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
System.out.println();
System.out.println("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by
// Prerna Saini.
Output:
Original Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary space: O(1) because using constant variables
Please refer complete article on Insert a node after the n-th node from the end for more details!
Similar Reads
Java Program For Inserting Node In The Middle Of The Linked List 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->
5 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 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 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 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 Printing Nth Node From The End Of A Linked List(Duplicate) Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is "B" Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1 (Use length
2 min read
Java Program For Printing Nth Node From The End Of A Linked List Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below the list and n = 3, then the output is "B". Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Method 1 (Use
5 min read
Java Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc
5 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 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