我可能只是对这里发生的事情完全无知,但我已经查看了一百万次并且我确定它是显而易见的但是我的插入方法由于while循环而无限循环。任何帮助将不胜感激。
这是代码..
package dcjaniszewskiOL4;
public class DoublyLinkedList<T extends Comparable> {
private class Node<T>
{
private T data;
private Node<T> next;
private Node<T> prev;
private Node(T d){
data=d;
next=null;
prev=null;
}
private Node( T d, Node<T> pref, Node<T> nref){
data=d;
prev=pref;
next=nref;
}
}
private Node<T> head;
private Node<T> current;
private int size;
public DoublyLinkedList(){
head = new Node<T>(null,null,null);
current=head.next;
size=0;
}
public DoublyLinkedList(DoublyLinkedList<T> i){
}
public void insert (T d){
Node<T> ptr, trav, prev;
prev=null;
begin();
trav=head.next;
if(empty()){
head.next = new Node<T>(d,head,head);
}
while(trav!=null){
System.out.println(trav.data);
prev=trav;
advance();
trav=current;
}
ptr = new Node<T> (d, prev,head);
if(prev==null){
head.next=ptr;
head.prev=ptr;
}
else{
prev.next=ptr;
current.prev=ptr;
}
size++;
}
public void remove(T d) throws ListEmptyException, NotInListException{
Node<T> tmp = head;
if(head.next==null){
throw new ListEmptyException("List is empty on Remove");
}
while(tmp!=null){
if(tmp.data.equals(d)){
tmp.prev.next=tmp.next;
tmp.next.prev=tmp.prev;
size--;
}else{
tmp=tmp.next;
if(tmp==null){
throw new NotInListException("Item is not in the list");
}
}
}
}
public void begin(){
current=head.next;
}
public void advance(){
current.prev = current;
current=current.next;
}
public void retreat(){
current.next=current;
current=current.prev;
}
public T current() throws ListEmptyException{
if(current==null){
throw new ListEmptyException("List is empty");
}else{
return current.data;
}
}
public boolean end(){
boolean end = false;
if(current==null){
end=true;
}else{
end=false;
}
return end;
}
public boolean empty(){
boolean empty = false;
if(size()==0){
empty=true;
}else{
empty=false;
}
return empty;
}
public int size(){
return size;
}
}
答案 0 :(得分:0)
试试这个
ptr = new Node<T> (d, null,null);
trav=head;
while (trav.next!= null)
{
trav = trav.next;
}
trav.next = ptr;
ptr.prev = trav;
如果它不起作用,请告诉我