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.

linked list before insert nth last position linked list after insert nth last position

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 

// Linked list node
class LinkNode
{
    public int data;
    public LinkNode next;
    public LinkNode(int data)
    {
        this.data = data;
        this.next = null;
    }
}
public class LinkedList
{
    public LinkNode head;
    public LinkedList()
    {
        this.head = null;
    }
    // insert node at end position
    public void insert(int value)
    {
        // Create a node
        LinkNode node = new LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            LinkNode temp = this.head;
            // find last node
            while (temp.next != null)
            {
                // Visit to next node
                temp = temp.next;
            }
            // add node
            temp.next = node;
        }
    }
    // Display linked list element
    public void display()
    {
        if (this.head == null)
        {
            return;
        }
        LinkNode temp = this.head;
        // iterating linked list elements
        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)
    {
        if (this.head == null)
        {
            System.out.print("Empty Linked list");
        }
        else if (position <= 0)
        {
            System.out.print("\nInvalid position");
        }
        else
        {
            LinkNode temp = head;
            LinkNode location = null;
            while (temp != null)
            {
                position--;
                if (position <= 0)
                {
                    if (location == null)
                    {
                        location = head;
                    }
                    else
                    {
                        location = location.next;
                    }
                }
                // visit to next node
                temp = temp.next;
            }
            if (position <= 1)
            {
                LinkNode node = new LinkNode(value);
                if (location == null)
                {
                    // Add node at first place
                    node.next = this.head;
                    this.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location.next;
                    location.next = node;
                }
            }
            else
            {
                System.out.print("\nOpps position not found");
            }
        }
    }
    public static void main(String[] args)
    {
        LinkedList sll = new LinkedList();
        // Add node
        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
java add linked list node at nth last position
// Include header file
#include <iostream>
using namespace std;
// C++ program for
// insert linked list node at nth last position

// Linked list node
class LinkNode
{
    public: int data;
    LinkNode *next;
    LinkNode(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
class LinkedList
{
    public: LinkNode *head;
    LinkedList()
    {
        this->head = NULL;
    }
    // insert node at end position
    void insert(int value)
    {
        // Create a node
        LinkNode *node = new LinkNode(value);
        if (this->head == NULL)
        {
            this->head = node;
        }
        else
        {
            LinkNode *temp = this->head;
            // find last node
            while (temp->next != NULL)
            {
                // Visit to next node
                temp = temp->next;
            }
            // add node
            temp->next = node;
        }
    }
    // Display linked list element
    void display()
    {
        if (this->head == NULL)
        {
            return;
        }
        LinkNode *temp = this->head;
        // iterating linked list elements
        while (temp != NULL)
        {
            cout << " " << temp->data << " →";
            // Visit to next node
            temp = temp->next;
        }
        cout << " NULL\n";
    }
    void endPosition(int position, int value)
    {
        if (this->head == NULL)
        {
            cout << "Empty Linked list";
        }
        else if (position <= 0)
        {
            cout << "\nInvalid position";
        }
        else
        {
            LinkNode *temp = this->head;
            LinkNode *location = NULL;
            while (temp != NULL)
            {
                position--;
                if (position <= 0)
                {
                    if (location == NULL)
                    {
                        location = this->head;
                    }
                    else
                    {
                        location = location->next;
                    }
                }
                // visit to next node
                temp = temp->next;
            }
            if (position <= 1)
            {
                LinkNode *node = new LinkNode(value);
                if (location == NULL)
                {
                    // Add node at first place
                    node->next = this->head;
                    this->head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node->next = location->next;
                    location->next = node;
                }
            }
            else
            {
                cout << "\nOpps position not found";
            }
        }
    }
};
int main()
{
    LinkedList *sll = new LinkedList();
    // Add node
    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;
        if ( *head == NULL)
        {
            *head = node;
        }
        else
        {
            struct Node *temp = *head;
            //find last node
            while (temp->next != NULL)
            {
                temp = temp->next;
            }
            //add node at last possition
            temp->next = node;
        }
    }
}
//display element of Node
void display(struct Node *temp)
{
    if (temp == NULL)
    {
        printf("\nEmpty linked list");
    }
    while (temp != NULL)
    {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
}
void add_nth_last(struct Node **head, int position, int value)
{
    if ( *head == NULL)
    {
        printf("\nEmpty Linked List");
    }
    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)
                {
                    location = *head;
                }
                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
                    node->next = *head;*head = node;
                }
                else
                {
                    node->next = location->next;
                    location->next = node;
                }
                //display all node
                display( *head);
            }
        }
    }
}
int main()
{
    //create node pointer
    struct Node *head = NULL;
    //insert element of linked list
    insert( &head, 5);
    insert( &head, 4);
    insert( &head, 3);
    insert( &head, 2);
    insert( &head, 1);
    printf("Before Linked List node :");
    //Display all node
    display(head);
    //Assume that position is positive integer
    int position = 2, data = 10;
    printf("\nAfter insert node at %d end position :", position);
    add_nth_last( & head, position, data);
}

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 

// Linked list node
public class LinkNode
{
    public int data;
    public LinkNode next;
    public LinkNode(int data)
    {
        this.data = data;
        this.next = null;
    }
}
public class LinkedList
{
    public LinkNode head;
    public LinkedList()
    {
        this.head = null;
    }
    // insert node at end position
    public void insert(int value)
    {
        // Create a node
        LinkNode node = new LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            LinkNode temp = this.head;
            // find last node
            while (temp.next != null)
            {
                // Visit to next node
                temp = temp.next;
            }
            // add node
            temp.next = node;
        }
    }
    // Display linked list element
    public void display()
    {
        if (this.head == null)
        {
            return;
        }
        LinkNode temp = this.head;
        // iterating linked list elements
        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)
    {
        if (this.head == null)
        {
            Console.Write("Empty Linked list");
        }
        else if (position <= 0)
        {
            Console.Write("\nInvalid position");
        }
        else
        {
            LinkNode temp = this.head;
            LinkNode location = null;
            while (temp != null)
            {
                position--;
                if (position <= 0)
                {
                    if (location == null)
                    {
                        location = this.head;
                    }
                    else
                    {
                        location = location.next;
                    }
                }
                // visit to next node
                temp = temp.next;
            }
            if (position <= 1)
            {
                LinkNode node = new LinkNode(value);
                if (location == null)
                {
                    // Add node at first place
                    node.next = this.head;
                    this.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location.next;
                    location.next = node;
                }
            }
            else
            {
                Console.Write("\nOpps position not found");
            }
        }
    }
    public static void Main(String[] args)
    {
        LinkedList sll = new LinkedList();
        // Add node
        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 

// Linked list node
type LinkNode struct {
    data int
    next * LinkNode
}
func getLinkNode(data int) * LinkNode {
    var me *LinkNode = &LinkNode {}
    me.data = data
    me.next = nil
    return me
}
type LinkedList struct {
    head * LinkNode
}
func getLinkedList() * LinkedList {
    var me *LinkedList = &LinkedList {}
    me.head = nil
    return me
}
// insert node at end position
func(this *LinkedList) insert(value int) {
    // Create a node
    var node * LinkNode = getLinkNode(value)
    if this.head == nil {
        this.head = node
    } else {
        var temp * LinkNode = this.head
        // find last node
        for (temp.next != nil) {
            // Visit to next node
            temp = temp.next
        }
        // add node
        temp.next = node
    }
}
// Display linked list element
func(this LinkedList) display() {
    if this.head == nil {
        return
    }
    var temp * LinkNode = this.head
    // iterating linked list elements
    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) {
    if this.head == nil {
        fmt.Print("Empty Linked list")
    } else if position <= 0 {
        fmt.Print("\nInvalid position")
    } else {
        var temp * LinkNode = this.head
        var location * LinkNode = nil
        for (temp != nil) {
            position--
            if position <= 0 {
                if location == nil {
                    location = this.head
                } else {
                    location = location.next
                }
            }
            // visit to next node
            temp = temp.next
        }
        if position <= 1 {
            var node * LinkNode = getLinkNode(value)
            if location == nil {
                // Add node at first place
                node.next = this.head
                this.head = node
            } else {
                // Add node at intermediate position
                node.next = location.next
                location.next = node
            }
        } else {
            fmt.Print("\nOpps position not found")
        }
    }
}
func main() {
    var sll * LinkedList = getLinkedList()
    // Add node
    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 

// Linked list node
class LinkNode
{
    public $data;
    public $next;
    public  function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }
}
class LinkedList
{
    public $head;
    public  function __construct()
    {
        $this->head = NULL;
    }
    // insert node at end position
    public  function insert($value)
    {
        // Create a node
        $node = new LinkNode($value);
        if ($this->head == NULL)
        {
            $this->head = $node;
        }
        else
        {
            $temp = $this->head;
            // find last node
            while ($temp->next != NULL)
            {
                // Visit to next node
                $temp = $temp->next;
            }
            // add node
            $temp->next = $node;
        }
    }
    // Display linked list element
    public  function display()
    {
        if ($this->head == NULL)
        {
            return;
        }
        $temp = $this->head;
        // iterating linked list elements
        while ($temp != NULL)
        {
            echo(" ".$temp->data.
                " →");
            // Visit to next node
            $temp = $temp->next;
        }
        echo(" NULL\n");
    }
    public  function endPosition($position, $value)
    {
        if ($this->head == NULL)
        {
            echo("Empty Linked list");
        }
        else if ($position <= 0)
        {
            echo("\nInvalid position");
        }
        else
        {
            $temp = $this->head;
            $location = NULL;
            while ($temp != NULL)
            {
                $position--;
                if ($position <= 0)
                {
                    if ($location == NULL)
                    {
                        $location = $this->head;
                    }
                    else
                    {
                        $location = $location->next;
                    }
                }
                // visit to next node
                $temp = $temp->next;
            }
            if ($position <= 1)
            {
                $node = new LinkNode($value);
                if ($location == NULL)
                {
                    // Add node at first place
                    $node->next = $this->head;
                    $this->head = $node;
                }
                else
                {
                    // Add node at intermediate position
                    $node->next = $location->next;
                    $location->next = $node;
                }
            }
            else
            {
                echo("\nOpps position not found");
            }
        }
    }
}

function main()
{
    $sll = new LinkedList();
    // Add node
    $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);
    echo("\n Add ".$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 

// Linked list node
class LinkNode
{
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}
class LinkedList
{
    constructor()
    {
        this.head = null;
    }
    // insert node at end position
    insert(value)
    {
        // Create a node
        var node = new LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            var temp = this.head;
            // find last node
            while (temp.next != null)
            {
                // Visit to next node
                temp = temp.next;
            }
            // add node
            temp.next = node;
        }
    }
    // Display linked list element
    display()
    {
        if (this.head == null)
        {
            return;
        }
        var temp = this.head;
        // iterating linked list elements
        while (temp != null)
        {
            process.stdout.write(" " + temp.data + " →");
            // Visit to next node
            temp = temp.next;
        }
        process.stdout.write(" NULL\n");
    }
    endPosition(position, value)
    {
        if (this.head == null)
        {
            process.stdout.write("Empty Linked list");
        }
        else if (position <= 0)
        {
            process.stdout.write("\nInvalid position");
        }
        else
        {
            var temp = this.head;
            var location = null;
            while (temp != null)
            {
                position--;
                if (position <= 0)
                {
                    if (location == null)
                    {
                        location = this.head;
                    }
                    else
                    {
                        location = location.next;
                    }
                }
                // visit to next node
                temp = temp.next;
            }
            if (position <= 1)
            {
                var node = new LinkNode(value);
                if (location == null)
                {
                    // Add node at first place
                    node.next = this.head;
                    this.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location.next;
                    location.next = node;
                }
            }
            else
            {
                process.stdout.write("\nOpps position not found");
            }
        }
    }
}

function main()
{
    var sll = new LinkedList();
    // Add node
    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 

#  Linked list node
class LinkNode :
    def __init__(self, data) :
        self.data = data
        self.next = None
    

class LinkedList :
    def __init__(self) :
        self.head = None
    
    #  insert node at end position
    def insert(self, value) :
        #  Create a node
        node = LinkNode(value)
        if (self.head == None) :
            self.head = node
        else :
            temp = self.head
            #  find last node
            while (temp.next != None) :
                #  Visit to next node
                temp = temp.next
            
            #  add node
            temp.next = node
        
    
    #  Display linked list element
    def display(self) :
        if (self.head == None) :
            return
        
        temp = self.head
        #  iterating linked list elements
        while (temp != None) :
            print("", temp.data ,"→", end = "")
            #  Visit to next node
            temp = temp.next
        
        print(" NULL")
    
    def endPosition(self, position, value) :
        if (self.head == None) :
            print("Empty Linked list", end = "")
        elif (position <= 0) :
            print("\nInvalid position", end = "")
        else :
            temp = self.head
            location = None
            while (temp != None) :
                position -= 1
                if (position <= 0) :
                    if (location == None) :
                        location = self.head
                    else :
                        location = location.next
                    
                
                #  visit to next node
                temp = temp.next
            
            if (position <= 1) :
                node = LinkNode(value)
                if (location == None) :
                    #  Add node at first place
                    node.next = self.head
                    self.head = node
                else :
                    #  Add node at intermediate position
                    node.next = location.next
                    location.next = node
                
            else :
                print("\nOpps position not found", end = "")
            
        
    

def main() :
    sll = LinkedList()
    #  Add node
    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 

#  Linked list node
class LinkNode 
    # Define the accessor and reader of class LinkNode
    attr_reader :data, :next
    attr_accessor :data, :next
    def initialize(data) 
        self.data = data
        self.next = nil
    end

end

class LinkedList 
    # Define the accessor and reader of class LinkedList
    attr_reader :head
    attr_accessor :head
    def initialize() 
        self.head = nil
    end

    #  insert node at end position
    def insert(value) 
        #  Create a node
        node = LinkNode.new(value)
        if (self.head == nil) 
            self.head = node
        else
 
            temp = self.head
            #  find last node
            while (temp.next != nil) 
                #  Visit to next node
                temp = temp.next
            end

            #  add node
            temp.next = node
        end

    end

    #  Display linked list element
    def display() 
        if (self.head == nil) 
            return
        end

        temp = self.head
        #  iterating linked list elements
        while (temp != nil) 
            print(" ", temp.data ," →")
            #  Visit to next node
            temp = temp.next
        end

        print(" NULL\n")
    end

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

                end

                #  visit to next node
                temp = temp.next
            end

            if (position <= 1) 
                node = LinkNode.new(value)
                if (location == nil) 
                    #  Add node at first place
                    node.next = self.head
                    self.head = node
                else
 
                    #  Add node at intermediate position
                    node.next = location.next
                    location.next = node
                end

            else
 
                print("\nOpps position not found")
            end

        end

    end

end

def main() 
    sll = LinkedList.new()
    #  Add node
    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 

// Linked list node
class LinkNode(var data: Int,
    var next: LinkNode)
{
    def this(data: Int)
    {
        this(data, null);
    }
}
class LinkedList(var head: LinkNode)
{
    def this()
    {
        this(null);
    }
    // insert node at end position
    def insert(value: Int): Unit = {
        // Create a node
        var node: LinkNode = new LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            var temp: LinkNode = this.head;
            // find last node
            while (temp.next != null)
            {
                // Visit to next node
                temp = temp.next;
            }
            // add node
            temp.next = node;
        }
    }
    // Display linked list element
    def display(): Unit = {
        if (this.head == null)
        {
            return;
        }
        var temp: LinkNode = this.head;
        // iterating linked list elements
        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;
        if (this.head == null)
        {
            print("Empty Linked list");
        }
        else if (position <= 0)
        {
            print("\nInvalid position");
        }
        else
        {
            var temp: LinkNode = head;
            var location: LinkNode = null;
            while (temp != null)
            {
                position -= 1;
                if (position <= 0)
                {
                    if (location == null)
                    {
                        location = head;
                    }
                    else
                    {
                        location = location.next;
                    }
                }
                // visit to next node
                temp = temp.next;
            }
            if (position <= 1)
            {
                var node: LinkNode = new LinkNode(value);
                if (location == null)
                {
                    // Add node at first place
                    node.next = this.head;
                    this.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location.next;
                    location.next = node;
                }
            }
            else
            {
                print("\nOpps position not found");
            }
        }
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var sll: LinkedList = new LinkedList();
        // Add node
        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

// Linked list node
class LinkNode
{
    var data: Int;
    var next: LinkNode? ;
    init(_ data: Int)
    {
        self.data = data;
        self.next = nil;
    }
}
class LinkedList
{
    var head: LinkNode? ;
    init()
    {
        self.head = nil;
    }
    // insert node at end position
    func insert(_ value: Int)
    {
        // Create a node
        let node: LinkNode = LinkNode(value);
        if (self.head == nil)
        {
            self.head = node;
        }
        else
        {
            var temp: LinkNode? = self.head;
            // find last node
            while (temp!.next  != nil)
            {
                // Visit to next node
                temp = temp!.next;
            }
            // add node
            temp!.next = node;
        }
    }
    // Display linked list element
    func display()
    {
        if (self.head == nil)
        {
            return;
        }
        var temp: LinkNode? = self.head;
        // iterating linked list elements
        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;
        if (self.head == nil)
        {
            print("Empty Linked list", terminator: "");
        }
        else if (position <= 0)
        {
            print("\nInvalid position", terminator: "");
        }
        else
        {
            var temp: LinkNode? = self.head;
            var location: LinkNode? = nil;
            while (temp  != nil)
            {
                position -= 1;
                if (position <= 0)
                {
                    if (location == nil)
                    {
                        location = self.head;
                    }
                    else
                    {
                        location = location!.next;
                    }
                }
                // visit to next node
                temp = temp!.next;
            }
            if (position <= 1)
            {
                let node: LinkNode = LinkNode(value);
                if (location == nil)
                {
                    // Add node at first place
                    node.next = self.head;
                    self.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location!.next;
                    location!.next = node;
                }
            }
            else
            {
                print("\nOpps position not found", terminator: "");
            }
        }
    }
}
func main()
{
    let sll: LinkedList = LinkedList();
    // Add node
    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 

// Linked list node
class LinkNode
{
    var data: Int;
    var next: LinkNode ? ;
    constructor(data: Int)
    {
        this.data = data;
        this.next = null;
    }
}
class LinkedList
{
    var head: LinkNode ? ;
    constructor()
    {
        this.head = null;
    }
    // insert node at end position
    fun insert(value: Int): Unit
    {
        // Create a node
        val node: LinkNode = LinkNode(value);
        if (this.head == null)
        {
            this.head = node;
        }
        else
        {
            var temp: LinkNode ? = this.head;
            // find last node
            while (temp?.next != null)
            {
                // Visit to next node
                temp = temp.next;
            }
            // add node
            temp?.next = node;
        }
    }
    // Display linked list element
    fun display(): Unit
    {
        if (this.head == null)
        {
            return;
        }
        var temp: LinkNode ? = this.head;
        // iterating linked list elements
        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;
        if (this.head == null)
        {
            print("Empty Linked list");
        }
        else if (position <= 0)
        {
            print("\nInvalid position");
        }
        else
        {
            var temp: LinkNode ? = this.head;
            var location: LinkNode ? = null;
            while (temp != null)
            {
                position -= 1;
                if (position <= 0)
                {
                    if (location == null)
                    {
                        location = this.head;
                    }
                    else
                    {
                        location = location.next;
                    }
                }
                // visit to next node
                temp = temp.next;
            }
            if (position <= 1)
            {
                val node: LinkNode = LinkNode(value);
                if (location == null)
                {
                    // Add node at first place
                    node.next = this.head;
                    this.head = node;
                }
                else
                {
                    // Add node at intermediate position
                    node.next = location.next;
                    location.next = node;
                }
            }
            else
            {
                print("\nOpps position not found");
            }
        }
    }
}
fun main(args: Array < String > ): Unit
{
    val sll: LinkedList = LinkedList();
    // Add node
    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.

New Comment







© 2021, kalkicode.com, All rights reserved