我是一名从头开始编程实施的初级程序员,由于某些原因,我遇到了一个错误的错误。这是我的班级:
class Queue
{
// pointer to first node in stack
public Node oldest;
public Node youngest;
public int queueSize = 0;
// constructor
public Queue(){
oldest = null;
youngest = null;
queueSize = 0;
}
public boolean isEmpty() {
return oldest == null;
}
public boolean add(Node newNode){
if(isEmpty()){
oldest = newNode;
}else{
newNode.next = youngest;
oldest.next = youngest;
youngest = newNode;
}
return true;
}
public Node remove(){
Node temp;
temp = oldest;
if( oldest != null){
oldest = oldest.next;
temp.next = null;
}
queueSize--;
return temp;
}
public void showQueue(){
Node p;
for(p = oldest; p != null; p = p.next){
p.toString();
}
}
}
如果我使用循环填充队列,然后执行showQueue(),我总是比我应该的少一个。例如,这来自我的主要:
// build the queue
for (int k = 0; k < 5; k++)
{
node1 = new Node();
queue2.add(node1);
}
//show the stack
queue2.showQueue();
给出结果
(节点)(节点)(节点)(节点)
或只有四个节点。这里发生了什么?
提前致谢。