I am trying to write a linked list using an array-based linked list. So far i have the code to create the list and insert an element but i get an exception when the list is not empty and has elements in it. Below is the code. Also how can i print the elements of the list to see if they are actually sorted?
EDIT: The code works now, i just cant get to show the elements stored in the list.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
public ArrayLL(){
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException{
if(size == 0){
ANode a = new ANode(s, -1);
list[0] = a;
size++;
}else if(size == MAX_CAP + 1){
throw new IOException("List is full");
}else{
for(int i = 0; i < this.getSize()-1; i++){
if(list[i].getData().compareTo(s) > 0){
for(int j = this.getSize(); j > i; j--){
list[j] = list[j+1];
}
ANode b = new ANode(s,i+1);
list[i] = b;
size++;
break;
}else{
ANode c = new ANode(s,-1);
list[size+1] = c;
size++;
}
}
}
}
public int getSize(){
return size;
}
}
class ANode{
private String data;
private int link;
public ANode(String d, int l){
data = d;
link = l;
}
public String getData(){
return data;
}
public int getLink(){
return link;
}
}