# Insert a node at last nth position of linked list

In previous post mention about that, how to insert new created linked list node at beginning, middle position and end position of linked list. That is new problem, add new created node at nth last position in existing linked list. We can solve this problem in a two way.

First method : counting the all linked list nodes and check given position are valid or not. If position are valid ,then iterates by loop and find the ( counted node - given position ) node. And add a new node at that position. This methods are iterated loop in two times. time complexity is O(n).

Method 2: Use two pointers, And head pointer reference are assigned to both pointers. One pointer are used to iterates the linked list element is one by one and visited to next upcoming node.

And given position are decrement one by one. when position value are have 0 that meas given position are valid to situation and stopped the decrement position value. But first pointer are continue to visit. And respect to first pointer start moving on second pointer one by one until the first pointer are not NULL. If first pointer are NULL then add new element after that second pointer. This process only one loop are used to check valid position and inserted node to valid position. That is better approach as compare to first method.

In this post are implementing of the second approach. Suppose we are inserted the following (5, 4, 3, 2, 1) node in a sequence.

Consider following test cases before write your code.

1) When linked list empty so in this case never find nth last node. so simple display empty linked list. You are also modified this test case when inserted position are 0 and adding new element to front of linked list. But we are assume that given position are always positive (more than zero).

2) When given position are one and linked list are not empty in this situation add new node to end of linked list. For example.

``````Linked list :   5  4  3  2  1 -->NULL
//position = 1 , data=10
After add   :   5  4  3  2  1  10 -->NULL
``````

3) When total number of linked list node +1 are given position value then in this case add element at beginning of linked list.

``````Linked list :   5  4  3  2  1 -->NULL
//position = 6 , data=10
After add   :  10  5  4  3  2  1-->NULL``````

4) When given position more greater than (total node+1) In this situation not insert new node.

Here given code implementation process.

``````// Java program for
// insert linked list node at nth last position

{
public int data;
{
this.data = data;
this.next = null;
}
}
{
{
}
// insert node at end position
public void insert(int value)
{
// Create a node
{
}
else
{
// find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
temp.next = node;
}
}
public void display()
{
{
return;
}
while (temp != null)
{
System.out.print(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
System.out.print(" NULL\n");
}
public void endPosition(int position, int value)
{
{
}
else if (position <= 0)
{
System.out.print("\nInvalid position");
}
else
{
while (temp != null)
{
position--;
if (position <= 0)
{
if (location == null)
{
}
else
{
location = location.next;
}
}
// visit to next node
temp = temp.next;
}
if (position <= 1)
{
if (location == null)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location.next;
location.next = node;
}
}
else
{
}
}
}
public static void main(String[] args)
{
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
int position = 2;
int data = 10;
sll.endPosition(position, data);
System.out.println("\n Add " + data +
" at last " + position + "-nd position");
sll.display();
}
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````// Include header file
#include <iostream>
using namespace std;
// C++ program for
// insert linked list node at nth last position

{
public: int data;
{
this->data = data;
this->next = NULL;
}
};
{
{
}
// insert node at end position
void insert(int value)
{
// Create a node
{
}
else
{
// find last node
while (temp->next != NULL)
{
// Visit to next node
temp = temp->next;
}
temp->next = node;
}
}
void display()
{
{
return;
}
while (temp != NULL)
{
cout << " " << temp->data << " →";
// Visit to next node
temp = temp->next;
}
cout << " NULL\n";
}
void endPosition(int position, int value)
{
{
}
else if (position <= 0)
{
cout << "\nInvalid position";
}
else
{
while (temp != NULL)
{
position--;
if (position <= 0)
{
if (location == NULL)
{
}
else
{
location = location->next;
}
}
// visit to next node
temp = temp->next;
}
if (position <= 1)
{
if (location == NULL)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node->next = location->next;
location->next = node;
}
}
else
{
}
}
}
};
int main()
{
sll->insert(5);
sll->insert(4);
sll->insert(3);
sll->insert(2);
sll->insert(1);
sll->display();
int position = 2;
int data = 10;
sll->endPosition(position, data);
cout << "\n Add " << data << " at last "
<< position << "-nd position" << endl;
sll->display();
return 0;
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````// C program for
// Linked list insert node at last nth position
#include<stdio.h>
#include <stdlib.h>

//create structure
struct Node
{
int data;
struct Node *next;
};
//function prototype
void insert(struct Node **, int);
void display(struct Node *);
void add_nth_last(struct Node **, int, int);
//insert Node element
void insert(struct Node **head, int value)
{
//Create dynamic node
struct Node *node = (struct Node *) malloc(sizeof(struct Node));
if (node == NULL)
{
printf("Memory overflow\n");
}
else
{
node->data = value;
node->next = NULL;
{
}
else
{
//find last node
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = node;
}
}
}
//display element of Node
void display(struct Node *temp)
{
if (temp == NULL)
{
}
while (temp != NULL)
{
printf("%d  ", temp->data);
temp = temp->next;
}
}
{
{
}
else if (position <= 0)
{
printf("\nPlease give of a valid node position");
}
else
{
struct Node *temp = *head, *location = NULL;
while (temp != NULL)
{
position--;
if (position <= 0)
{
if (location == NULL)
{
}
else
{
location = location->next;
}
}
temp = temp->next;
}
if (position > 1)
{
printf("\nInvalid position");
}
else
{
struct Node *node = (struct Node *) malloc(sizeof(struct Node));
if (node == NULL)
{
printf("\nMemory overflow\n");
}
else
{
node->data = value;
if (location == NULL)
{
//insert node at begining
}
else
{
node->next = location->next;
location->next = node;
}
//display all node
}
}
}
}
int main()
{
//create node pointer
//Display all node
//Assume that position is positive integer
int position = 2, data = 10;
printf("\nAfter insert node at %d end position :", position);
}``````

#### Output

``````Before Linked List node :5  4  3  2  1
After insert node at 2 end position :5  4  3  2  10  1``````
``````// Include namespace system
using System;
// Csharp program for
// insert linked list node at nth last position

{
public int data;
{
this.data = data;
this.next = null;
}
}
{
{
}
// insert node at end position
public void insert(int value)
{
// Create a node
{
}
else
{
// find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
temp.next = node;
}
}
public void display()
{
{
return;
}
while (temp != null)
{
Console.Write(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
Console.Write(" NULL\n");
}
public void endPosition(int position, int value)
{
{
}
else if (position <= 0)
{
Console.Write("\nInvalid position");
}
else
{
while (temp != null)
{
position--;
if (position <= 0)
{
if (location == null)
{
}
else
{
location = location.next;
}
}
// visit to next node
temp = temp.next;
}
if (position <= 1)
{
if (location == null)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location.next;
location.next = node;
}
}
else
{
}
}
}
public static void Main(String[] args)
{
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
int position = 2;
int data = 10;
sll.endPosition(position, data);
Console.WriteLine("\n Add " + data +
" at last " + position + "-nd position");
sll.display();
}
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````package main
import "fmt"
// Go program for
// insert linked list node at nth last position

data int
}
me.data = data
me.next = nil
return me
}
}
return me
}
// insert node at end position
// Create a node
} else {
// find last node
for (temp.next != nil) {
// Visit to next node
temp = temp.next
}
temp.next = node
}
}
return
}
for (temp != nil) {
fmt.Print(" ", temp.data, " →")
// Visit to next node
temp = temp.next
}
fmt.Print(" NULL\n")
}
func(this LinkedList) endPosition(position, value int) {
} else if position <= 0 {
fmt.Print("\nInvalid position")
} else {
var location * LinkNode = nil
for (temp != nil) {
position--
if position <= 0 {
if location == nil {
} else {
location = location.next
}
}
// visit to next node
temp = temp.next
}
if position <= 1 {
if location == nil {
// Add node at first place
} else {
// Add node at intermediate position
node.next = location.next
location.next = node
}
} else {
}
}
}
func main() {
sll.insert(5)
sll.insert(4)
sll.insert(3)
sll.insert(2)
sll.insert(1)
sll.display()
var position int = 2
var data int = 10
sll.endPosition(position, data)
fmt.Println("\n Add ", data, " at last ", position, "-nd position")
sll.display()
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````<?php
// Php program for
// insert linked list node at nth last position

{
public \$data;
public \$next;
public  function __construct(\$data)
{
\$this->data = \$data;
\$this->next = NULL;
}
}
{
public  function __construct()
{
}
// insert node at end position
public  function insert(\$value)
{
// Create a node
{
}
else
{
// find last node
while (\$temp->next != NULL)
{
// Visit to next node
\$temp = \$temp->next;
}
\$temp->next = \$node;
}
}
public  function display()
{
{
return;
}
while (\$temp != NULL)
{
echo(" ".\$temp->data.
" →");
// Visit to next node
\$temp = \$temp->next;
}
echo(" NULL\n");
}
public  function endPosition(\$position, \$value)
{
{
}
else if (\$position <= 0)
{
echo("\nInvalid position");
}
else
{
\$location = NULL;
while (\$temp != NULL)
{
\$position--;
if (\$position <= 0)
{
if (\$location == NULL)
{
}
else
{
\$location = \$location->next;
}
}
// visit to next node
\$temp = \$temp->next;
}
if (\$position <= 1)
{
if (\$location == NULL)
{
// Add node at first place
}
else
{
// Add node at intermediate position
\$node->next = \$location->next;
\$location->next = \$node;
}
}
else
{
}
}
}
}

function main()
{
\$sll->insert(5);
\$sll->insert(4);
\$sll->insert(3);
\$sll->insert(2);
\$sll->insert(1);
\$sll->display();
\$position = 2;
\$data = 10;
\$sll->endPosition(\$position, \$data);
" at last ".\$position.
"-nd position".
"\n");
\$sll->display();
}
main();``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````// Node JS program for
// insert linked list node at nth last position

{
constructor(data)
{
this.data = data;
this.next = null;
}
}
{
constructor()
{
}
// insert node at end position
insert(value)
{
// Create a node
{
}
else
{
// find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
temp.next = node;
}
}
display()
{
{
return;
}
while (temp != null)
{
process.stdout.write(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
process.stdout.write(" NULL\n");
}
endPosition(position, value)
{
{
}
else if (position <= 0)
{
process.stdout.write("\nInvalid position");
}
else
{
var location = null;
while (temp != null)
{
position--;
if (position <= 0)
{
if (location == null)
{
}
else
{
location = location.next;
}
}
// visit to next node
temp = temp.next;
}
if (position <= 1)
{
if (location == null)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location.next;
location.next = node;
}
}
else
{
}
}
}
}

function main()
{
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
var position = 2;
var data = 10;
sll.endPosition(position, data);
console.log("\n Add " + data + " at last " + position + "-nd position");
sll.display();
}
main();``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````#  Python 3 program for
#  insert linked list node at nth last position

def __init__(self, data) :
self.data = data
self.next = None

def __init__(self) :

#  insert node at end position
def insert(self, value) :
#  Create a node
else :
#  find last node
while (temp.next != None) :
#  Visit to next node
temp = temp.next

temp.next = node

def display(self) :
return

while (temp != None) :
print("", temp.data ,"→", end = "")
#  Visit to next node
temp = temp.next

print(" NULL")

def endPosition(self, position, value) :
print("Empty Linked list", end = "")
elif (position <= 0) :
print("\nInvalid position", end = "")
else :
location = None
while (temp != None) :
position -= 1
if (position <= 0) :
if (location == None) :
else :
location = location.next

#  visit to next node
temp = temp.next

if (position <= 1) :
if (location == None) :
#  Add node at first place
else :
#  Add node at intermediate position
node.next = location.next
location.next = node

else :

def main() :
sll.insert(5)
sll.insert(4)
sll.insert(3)
sll.insert(2)
sll.insert(1)
sll.display()
position = 2
data = 10
sll.endPosition(position, data)
print("\n Add ", data ," at last ", position ,"-nd position")
sll.display()

if __name__ == "__main__": main()``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add  10  at last  2 -nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````#  Ruby program for
#  insert linked list node at nth last position

attr_accessor :data, :next
def initialize(data)
self.data = data
self.next = nil
end

end

def initialize()
end

#  insert node at end position
def insert(value)
#  Create a node
else

#  find last node
while (temp.next != nil)
#  Visit to next node
temp = temp.next
end

temp.next = node
end

end

def display()
return
end

while (temp != nil)
print(" ", temp.data ," →")
#  Visit to next node
temp = temp.next
end

print(" NULL\n")
end

def endPosition(position, value)
elsif (position <= 0)
print("\nInvalid position")
else

location = nil
while (temp != nil)
position -= 1
if (position <= 0)
if (location == nil)
else

location = location.next
end

end

#  visit to next node
temp = temp.next
end

if (position <= 1)
if (location == nil)
#  Add node at first place
else

#  Add node at intermediate position
node.next = location.next
location.next = node
end

else

end

end

end

end

def main()
sll.insert(5)
sll.insert(4)
sll.insert(3)
sll.insert(2)
sll.insert(1)
sll.display()
position = 2
data = 10
sll.endPosition(position, data)
print("\n Add ", data ," at last ",
position ,"-nd position", "\n")
sll.display()
end

main()``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL
``````
``````// Scala program for
// insert linked list node at nth last position

{
def this(data: Int)
{
this(data, null);
}
}
{
def this()
{
this(null);
}
// insert node at end position
def insert(value: Int): Unit = {
// Create a node
{
}
else
{
// find last node
while (temp.next != null)
{
// Visit to next node
temp = temp.next;
}
temp.next = node;
}
}
def display(): Unit = {
{
return;
}
while (temp != null)
{
print(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
print(" NULL\n");
}
def endPosition(n: Int, value: Int): Unit = {
var position = n;
{
}
else if (position <= 0)
{
print("\nInvalid position");
}
else
{
while (temp != null)
{
position -= 1;
if (position <= 0)
{
if (location == null)
{
}
else
{
location = location.next;
}
}
// visit to next node
temp = temp.next;
}
if (position <= 1)
{
if (location == null)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location.next;
location.next = node;
}
}
else
{
}
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
var position: Int = 2;
var data: Int = 10;
sll.endPosition(position, data);
println("\n Add " + data + " at last " + position + "-nd position");
sll.display();
}
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````// Swift 4 program for
// Insert linked list node at nth last position

{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
}
}
{
init()
{
}
// insert node at end position
func insert(_ value: Int)
{
// Create a node
{
}
else
{
// find last node
while (temp!.next  != nil)
{
// Visit to next node
temp = temp!.next;
}
temp!.next = node;
}
}
func display()
{
{
return;
}
while (temp  != nil)
{
print("", temp!.data ,"→", terminator: "");
// Visit to next node
temp = temp!.next;
}
print(" NULL");
}
func endPosition(_ n: Int, _ value: Int)
{
var position = n;
{
}
else if (position <= 0)
{
print("\nInvalid position", terminator: "");
}
else
{
while (temp  != nil)
{
position -= 1;
if (position <= 0)
{
if (location == nil)
{
}
else
{
location = location!.next;
}
}
// visit to next node
temp = temp!.next;
}
if (position <= 1)
{
if (location == nil)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location!.next;
location!.next = node;
}
}
else
{
}
}
}
}
func main()
{
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
let position: Int = 2;
let data: Int = 10;
sll.endPosition(position, data);
print("\n Add ", data ," at last ", position ,"-nd position");
sll.display();
}
main();``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add  10  at last  2 -nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````
``````// Kotlin program for
// insert linked list node at nth last position

{
var data: Int;
constructor(data: Int)
{
this.data = data;
this.next = null;
}
}
{
constructor()
{
}
// insert node at end position
fun insert(value: Int): Unit
{
// Create a node
{
}
else
{
// find last node
while (temp?.next != null)
{
// Visit to next node
temp = temp.next;
}
temp?.next = node;
}
}
fun display(): Unit
{
{
return;
}
while (temp != null)
{
print(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
print(" NULL\n");
}
fun endPosition(n: Int, value: Int): Unit
{
var position = n;
{
}
else if (position <= 0)
{
print("\nInvalid position");
}
else
{
var location: LinkNode ? = null;
while (temp != null)
{
position -= 1;
if (position <= 0)
{
if (location == null)
{
}
else
{
location = location.next;
}
}
// visit to next node
temp = temp.next;
}
if (position <= 1)
{
if (location == null)
{
// Add node at first place
}
else
{
// Add node at intermediate position
node.next = location.next;
location.next = node;
}
}
else
{
}
}
}
}
fun main(args: Array < String > ): Unit
{
sll.insert(5);
sll.insert(4);
sll.insert(3);
sll.insert(2);
sll.insert(1);
sll.display();
val position: Int = 2;
val data: Int = 10;
sll.endPosition(position, data);
println("\n Add " + data + " at last " + position + "-nd position");
sll.display();
}``````

#### Output

`````` 5 → 4 → 3 → 2 → 1 → NULL

Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → NULL``````

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.