我的項目應該實現兩個類。基本的鏈接列表和排序的鏈接列表。一切似乎工作正常,除了某些原因,我無法遍歷排序的鏈接列表。班級結構如下:迭代器的鏈表
public class BasicLinkedList<T> implements Iterable<T> {
public int size;
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
next = null;
}
}
private Node head;
private Node tail;
public BasicLinkedList() {
head = tail = null;
}
//Add, remove method
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
@Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
現在,當我測試這個類時,它工作得很好。迭代器的工作原理和我可以測試一切。問題在於擴展了這個的排序後的鏈表類。下面是它的實現和我使用在構造一個比較類:
public class SortedLinkedList<T> extends BasicLinkedList<T>{
private class Node{
private T data;
private Node next;
private Node(T data){
this.data = data;
next = null;
}
}
private Node head;
private Node tail;
private Comparator<T> comp;
public SortedLinkedList(Comparator<T> comparator){
super();
this.comp = comparator;
}
這裏的比較級和我在一個單獨的類運行測試:
public class intComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
}
public static void main(String[] args) {
System.out.println("---------------SortedLinkedList--------------");
SortedLinkedList<Integer> sortedList = new SortedLinkedList<Integer>(new intComparator());
sortedList.add(3);
sortedList.add(5);
sortedList.add(2);
for(int i: sortedList){
System.out.println(i);
}
}
沒有打印出來。我認爲被繼承的迭代器將幫助我遍歷這個沒有問題,並明確它的合法性,因爲for-each循環編譯。只是沒有打印出來。我調試它,所有的添加,刪除的東西按預期工作。這只是迭代器沒有做它應該做的。我應該爲這個類創建一個單獨的新迭代器嗎?但是,既然我已經繼承了它,那會不會是多餘的代碼呢?幫助讚賞!
編輯:這裏有一個排序列表
public SortedLinkedList<T> add(T element){
Node n = new Node(element);
Node prev = null, curr = head;
if(head == null){
head = n;
tail = n;
}
//See if the element goes at the very front
else if(comp.compare(n.data, curr.data) <= 0){
n.next = head;
head = n;
}
//See if the element is to be inserted at the very end
else if(comp.compare(n.data, tail.data)>=0){
tail.next = n;
tail = n;
}
//If element is to be inserted in the middle
else{
while(comp.compare(n.data, curr.data) > 0){
prev = curr;
curr = curr.next;
}
prev.next = n;
n.next = curr;
}
size++;
return this;
}
您可以發佈[SSCCE(http://meta.stackexchange.com/questions/22754/sscce-how-to-provide-examples-for-programming-questions)?由於缺少'add'方法,我無法嘗試您的代碼。 –
發表於編輯@pubudu –