I tried to use my own implemented LinkedList.
public class LinkedList<O> {
private Node<O> first,last;
private int count;
public LinkedList(){}
public Node getfirst(){
if(first==null) return null;
else return first;
}
public Node getLast(){
if(first==null) return null;
else return last;
}
public int getSize(){
return count;
}
public void addFirst(Object x){
if(first==null)first=last=new Node(x);
else{
Node temp =new Node(x);
temp.next=first;
first=temp;
}
count++;
}
public void addLast(Object x){
if(first==null)first=last=new Node(x);
else{
last.next= new Node(x);
last=last.next;
}
count++;
}
public void add(Object x,int index){
if(index==0)addFirst(x);
else if(index>=getSize())addLast(x);
else{
Node current=first;
for(int i=0; i<index-1;i++)
current=current.next;
Node temp = new Node(x);
temp.next=current.next;
current.next=temp;
count++;
}
}
public boolean removeFirst(){
if(first==null)return false;
else if(first==last){
first=last=null;
count--;
return true;
}
else{
first=first.next;
count--;
return true;
}
}
public boolean removeLast(){
if(first==null)return false;
else if(first==last){
first=last=null;
count--;
return true;
}
else{
Node current=first;
for(int i=0;i<getSize()-2;i++)
current=current.next;
last=current;
last.next=null;
count--;
return true;
}
}
public boolean remove(int index){
if(index==0)return removeFirst();
else if(index==getSize()-1)return removeLast();
else{
Node current=first;
for(int i=0;i<index-1;i++)
current=current.next;
current.next=(current.next).next;
count--;
return true;
}
}
}
public class Node<E> {
E element;
Node<E> next;
public Node(E element) {
this.element = element;
}
}
when I used :
for(Book b:books){
System.out.println(b);
}
it gave me an error: Can only iterate over an array or an instance of java.lang.Iterable
So, I tried to use :
for(Book current=books.getFirst(); current !=null; current=current.next){
System.out.println(current);
}
It print :
project11.Node@139a55
project11.Node@1db9742
project11.Node@106d69c
and when I used collection.sort
Collections.sort(books,new Comparator<Book>()){
public int compare(Book book1, Book book2) {
return book1.getTitle().compareToIgnoreCase(book2.getTitle());
}
}
It gave me: The method sort(List, Comparator) in the type Collections is not applicable for the arguments (LinkedList, Stock.MyTitleComp)
Can someone explain these errors please and how to fix them.