Reputation: 143
Hi I have this method to insert an element at any index of the LinkedList, however, the new element is not showing in the output, what did i miss thanks! I have showed partial code below, any help is greatly appreciated!
public class LinkedList<E extends Comparable<E>> implements Iterable<E>
{
// instance data members of list
private Node head; // reference to the first node
private int N; // number of elements stored in the list
private class Node
{
// instance data members of Node
public E item;
public Node next;
// constructors for Node
public Node()
{
item = null; next = null;
}
public Node(E e, Node ptr)
{
item = e; next = ptr;
}
}// end class Node
public void insertAfter(int k, E e){
if (k < 0 || k >= size()){
throw new IndexOutOfBoundsException();}
Node temp=new Node();
temp.item=e;
int index=k-1;
Node current=head;
for (int i=0; i<=N; N++){
if (i==index){
temp.next=current.next;
current.next=temp;
}
}
++N;
}
Upvotes: 0
Views: 910
Reputation: 7071
You are not moving the current element throught the list. You loop the integer indexes but don't move the pointer to the current node. So in the loop current is always the head of the linked list. You need to make it like that:
for (int i=0; i<=N; N++)
if (i==index){
temp.next=current.next;
current.next=temp;
}else{
current=current.next;
}
This way when you add the element you will be in the proper position. Otherwise you will ways insert it in the first position.
Upvotes: 1
Reputation: 8202
It looks like you're incrementing an instance variable N
Try this instead
public void insertAfter(int k, E e){
if (k < 0 || k >= size()){
throw new IndexOutOfBoundsException();}
Node temp=new Node();
temp.item=e;
int index=k-1;
Node current=head;
for (int i=0; current != null && i<N; i++){
if (i==index){
temp.next=current.next;
current.next=temp;
} else {
current = current.next;
}
}
++N;
}
Don't forget that if you insert a node at position 0, you need to update what head
references.
Upvotes: 1