Inserting a new node in a linked list data structure

Inserting new node in linked list can do 3 ways.

1. At the start of the Linked list
2. In the middle of the Linked list
3. At the end of the Linked list

Before starting you have to must know about Linked list and how to create it.

1.  At Start of Linked list

```package in.eyehunt.data.struc;
class Node {
int data;
Node next;
// Parameterized constructor
Node(int d) {
data = d;
next = null;
}
}
// method to add new node in start
void push(int n) {
//create new node
Node newNode = new Node(n);
// move had point to new node
}
void printAllNodes() {
while (node != null) {
System.out.print("-> "+node.data);
node = node.next;
}
}
public static void main(String a[]) {
//create a simple linked list with 4 nodes
}
}
```

2.  In the Middle of Linked list

Insert a new node with data at the middle of the list and given a linked list containing n nodes..

So now condition is :

• 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.

Must read this tutorial to Find Length of a Linked List data for better understanding.

```package in.eyehunt.data.struc;
class Node {
int data;
Node next;

// Parameterized constructor
Node(int d) {
data = d;
next = null;
}
}
void push(int n) {
//create new node
Node newNode = new Node(n);
// move had point to new node
}

} else {
int middleNode = (count() % 2 == 0) ? (count() / 2) : ((count() + 1) / 2);

//create new node
Node newNode = new Node(n);
int countNodes = 0;
while (countNodes != middleNode -1) {
pointerNode = pointerNode.next;
countNodes ++;
}
System.out.println("\n Middle node of linked List " + middleNode);
System.out.println("\n Middle node data " + pointerNode.data);

// adding new node in middle
newNode.next = pointerNode.next;
pointerNode.next = newNode;
printAllNodes();
}
}
//Returns count of nodes in linked list (iteration)
public int count() {
int a = 0;
while (n != null) {
n = n.next;
a++;
}
return a;
}
void printAllNodes() {
while (node != null) {
System.out.print("-> " + node.data);
node = node.next;
}
}
public static void main(String a[]) {

//create a simple linked list with 4 nodes
}
}```

```package in.eyehunt.data.struc;
class Node {
int data;
Node next;
// Parameterized constructor
Node(int d) {
data = d;
next = null;
}
}
void append(int n) {
// create new node
Node newNode = new Node(n);
return;
}
//traverse till the last node
while (last.next != null) {
last = last.next;
}
//Add the new node of last node
last.next = newNode;
return;
}
void printAllNodes() {
while (node != null) {
System.out.print("-> "+node.data);
node = node.next;
}
}
public static void main(String a[]) {
//create a simple linked list with 4 nodes