I've got a class project where I have to build an ADT-based linked list from scratch (meaning I can't use any standard Java ADTs) and then use that to sort a bunch of State
objects (that each also contain a linked list of Cities
) alphabetically. The backbone of the code is, obviously, the handmade OrderedLinkedList
class, and I'm having a lot of trouble figuring out how to implement, speficially, a findOrAdd
method that iterates through the list and, if the argument passed is not already in the list, adds it in the appropriate spot (and returns the element if it's already there). Most of the things I've read about implementing linked lists don't deal in ADTs and so it's difficult to convert that in my mind and still wrap my head around it. My (admittedly incomplete) OLL code and its accompanying iterator:
import java.util.Iterator;
public class OrderedLinkedList<E extends Comparable<E>> implements Iterable<E>
{
private E first;
private E next;
private E last;
private E current;
private E temp;
private int size;
public OrderedLinkedList()
{
this.first = null;
this.next = null;
this.last = null;
this.current = null;
this.size = 0;
}
public E findOrAdd(E element)
{
E returnVal = null;
Iterator<E> listIter = this.iterator();
if (this.first == null)
{
this.first = element;
this.size++;
}
else
for (int i = 0; i < this.size; i++)
{
if (listIter.next().compareTo(element) == 1 && listIter.hasNext() == false)
{
temp = this.first;
this.first = element;
this.next = temp;
this.size++;
}
else if (listIter.next().compareTo(element) == 1 && listIter.hasNext() == true)
continue;
else if (listIter.next().compareTo(element) == 0)
returnVal = element;
else if (listIter.next().compareTo(element) == -1)
{
temp = this.next;
this.next = element;
}
}
return returnVal;
}
public Iterator<E> iterator()
{
return new OrdListIterator<E>();
}
private class OrdListIterator<E> implements Iterator<E>
{
private E nextNode;
public OrdListIterator()
{
//maybe something needed here
}
public boolean hasNext()
{
return (next != null);
}
public E next()
{
return (E) next;
}
public E first()
{
return (E) first;
}
public void remove()
{
//implement later
}
}
}
I've got compareTo() methods in the State
and City
classes that override the usual method but still function the same way. Where am I going wrong in findOrAdd
? How am I going wrong? I'm not looking for a full correction of the code or anything; I'm about 99% sure everything under that else
block is abysmal. I just need a push in the right direction: someplace to get a foothold. I'd hugely appreciate any advice.
答案 0 :(得分:1)