引起我相信錯誤是由不正確添加到隊列引起的,可能有其他錯誤,但我認爲這是這裏的東西空指針異常與隊列
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
,如果你需要的代碼的其他部分尋找這裏的錯誤是滿級
import java.util.*;
public class Queue<E>
{
private ListNode <E> front;
private ListNode <E> end;
private int size;
public Queue()
{
front = null;
end = null;
size = 0;
}
public E peek()
{
return front.getData();
}
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
// [data, data, data, data]
public String toString()
{
String s ="";
ListNode <E> temp = front;
while(temp.getNext()!= null)
{
s+=temp.getData() + ", ";
}
return s;
}
public int size()
{
return size;
}
}
,這裏是我使用
public class ListNode<E>
{
private E data;
private ListNode<E> next;
/**
* Constructs a ListNode with a specified data and next
* @param d the data for the node
* @param n the next reference
*/
public ListNode(E d, ListNode<E> n)
{
data = d;
n = next;
}
/**
* returns the data from the node
* @return the data field
*/
public E getData() {return data;}
/**
* sets the data for the node
* @param d the new data field
*/
public void setData(E d) {data = d;}
/**
* gets the next reference of the node
* @return the next reference
*/
public ListNode<E> getNext() { return next; }
/**
* sets the next reference for the node
* @param n the new next reference
*/
public void setNext(ListNode<E> n) { next = n;}
}
一個節點第二,這是我在用測試它
public class QueueTester
{
public static void main (String args[])
{
Queue<Integer> queue = new Queue<Integer>();
for (int k = 1; k <= 100; k++) // add 1 to 100
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 1; k <= 50; k++) // remove 1 to 50, contents 51 to 100
{
int number = queue.remove();
}
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 200; k <= 500; k+=10) // add tens 200 to 500 (after 51 to 100)
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
while (!queue.isEmpty()) // prints contents (should be 51 to 100, then 200 to 500 tens)
{
System.out.print(queue.remove() + " ");
}
System.out.println("\n");
System.out.println ("Size: " + queue.size());
System.out.println(queue); // empty
System.out.println ("Remove from empty queue: " + queue.remove() + "\n") ;
}
}
你不使用它之前初始化'end'。 – vandale
此外,大小永遠不會增加。 –