Linked List – Insertion at Nth position

Damith
1,343 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Overview

We discussed how to implement the Linked List in here. In this tutorial, we’re going to implement insertion a Node at given position.

Insert a Node at Nth Position

Steps

  1. If Head is null and position is not 0. Then exit it.
  2. If Head is null and position is 0. Then insert new Node to the Head and exit it.
  3. If Head is not null and position is 0. Then the Head reference set to the new Node. Finally, new Node set to the Head and exit it.
  4. If not, iterate until finding the Nth position or end.
public void insertNth(int data, int position) {
    //create new node.
    Node node = new Node();
    node.data = data;
    node.nextNode = null;

    if (this.head == null) {
      //if head is null and position is zero then exit.
      if (position != 0) {
       return;
      } else { //node set to the head.
       this.head = node;
      }
    }

    if (head != null && position == 0) {
      node.nextNode = this.head;
      this.head = node;
      return;
    }

    Node current = this.head;
    Node previous = null;

    int i = 0;

    while (i < position) {
      previous = current;
      current = current.nextNode;

      if (current == null) {
        break;
      }

       i++;
      }

      node.nextNode = current;
      previous.nextNode = node;
}

Complete Example

1
2
3
4
5
92
93
94
95
96
97
98
99
100
101
102
103
class Node {
int data;
Node nextNode;
}
class LinkedList {...}
public class Main {
public static void main(String[] args) {
LinkedList ls = new LinkedList();
ls.insert(10);
ls.insert(20);
ls.insert(30);
ls.print();
ls.insertNth(25, 2);
ls.print();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Original post can find it here

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content