Trying to insert an object at a specified index in a linked list java class. Not too sure how too implement this though.
Here is an example of the parameters for the method and what i have so far(doesn't work):
void insertAtIndex(int idx, Shape data){
if (idx == 0) {
//insert the new Shape at the beginning of the list
insertAtBeginning(data);
}else{
Node temp = head;
for(int i = 0; i < idx - 1; i++)
temp = temp.getNext();
Node next = new Node(data);
next = temp.getNext();
temp = next;
}
}
subclass for Node:
public Node(Shape data){
//Make next point to null
next = null;
this.data = data;
}
// another Node constructor if we want to specify the node to point to.
public Node(Shape dataVal, Node nextVal){
next = nextVal;
data = dataVal;
}
//Getter for data
public Shape getData(){
return data;
}
//Setter for data
public void setData(Shape data){
this.data = data;
}
//Getter for next
public Node getNext() {
return next;
}
//Setter for next
public void setNext(Node next) {
this.next = next;
}
linked list class:
public class ShapeLinkedList {
public Node head; //head is first node in linked list
public Node tail; //tail is last node in linked list
public ShapeLinkedList(){}
public ShapeLinkedList(Node head){
head = null;
tail = null;
}
public boolean isEmpty(){
return length() == 0;
}