Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
- If Head is null and position is not 0. Then exit it.
- If Head is null and position is 0. Then insert new Node to the Head and exit it.
- 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.
- 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
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Node {
int data;
Node nextNode;
}
class LinkedList {
private Node head;
// {
public void insert(int data) {
//create a new Node and store a data.
Node node = new Node();
node.data = data;
node.nextNode = null;
//check the head is null or not.
//if head is null, assign the Node and exit.
if (this.head == null) {
head = node;
return;
}
//assign a head into the temp Node and loop it until find the null reference.
Node tempNode = this.head;
while (tempNode.nextNode != null) {
tempNode = tempNode.nextNode;
}
//assign new node.
tempNode.nextNode = node;
}
// }
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;
Press desired key combination and then press ENTER.
Original post can find it here
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content