下面是 Stack 程序的代码。我的问题特别是关于 push 方法,在开始时,它检查是否(pContent!= null)。为什么这样做?我将 if 语句注释掉了,它仍然可以正常工作,那么使用它的原因是什么。另外,这里的 pContent 和 ContentType 有什么区别?
我试图理解我得到的这段代码,我非常感谢你的帮助。
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Stacko<ContentType> extends Actor {
/* --------- Anfang der privaten inneren Klasse -------------- */
private class StackNode {
private ContentType content = null;
private StackNode nextNode = null;
public StackNode(ContentType pContent) {
content = pContent;
nextNode = null;
}
public void setNext(StackNode pNext) {
nextNode = pNext;
}
public StackNode getNext() {
return nextNode;
}
public ContentType getContent() {
return content;
}
}
/* ----------- Ende der privaten inneren Klasse -------------- */
private StackNode head;
public void Stack() {
head = null;
}
public boolean isEmpty() {
return (head == null);
}
public void push(ContentType pContent) {
if (pContent != null) {
StackNode node = new StackNode(pContent);
node.setNext(head);
head = node;
}
}
public void pop() {
if (!isEmpty()) {
head = head.getNext();
}
}
public ContentType top() {
if (!this.isEmpty()) {
return head.getContent();
} else {
return null;
}
}
}