I have created a method to insert a node in LinkedList at Nth index. The code works fine for all the positions except 0th position. Please review my code below and let me know what's wrong. The below code has 2 insert methods:
insert(int data): This used to add a new node.insertAtNthPositon(int position, int data): This helps to insert the element at Nth position.
public class LinkedList {
Node head;
static class Node {
int data;
Node next;
}
public void insert(int data) {
Node new_node = new Node();
new_node.data = data;
new_node.next = null;
if (head == null) {
head = new_node;
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n.next = new_node;
}
}
public void insertAtNthPositon(int position, int data) {
Node new_node = new Node();
new_node.data = data;
Node current_node = head;
int i = 0;
if (position == 0) {
new_node.next = current_node.next;
head = new_node;
current_node = current_node.next;
}
while (i < position - 1) {
current_node = current_node.next;
i++;
}
new_node.next = current_node.next;
current_node.next = new_node;
}
public static void main(String[] arg) {
LinkedList ls = new LinkedList();
ls.insert(6);
ls.insert(7);
ls.insert(9);
ls.insertAtNthPositon(1, 100);
ls.show();
}
private void show() {
Node current = head;
StringBuilder sb = new StringBuilder();
do {
sb.append(current.data);
sb.append("->");
current = current.next;
} while (current != null);
sb.append("null");
System.out.println(sb.toString());
}
}
Output:
6->100->7->9->null
headis initialized tonull, then this line:new_node.next = current_node.next;will generate an NPE. You need to provide more in your code above to tell us what you're doing to determine why 0 is failing as an index for your homework assignment. Otherwise, you should be usingjava.util.ArrayList. - dan