java - 写一个动态栈链表java的push方法
问题描述
在尝试编写一个本质上推入动态堆栈的方法时,我遇到了一些麻烦。我不完全确定如何编写它,所以我想知道是否有人对如何推进这个有任何指示或提示。
这是课程的一部分
public class StackOfVersionedObjects {
private Node<VersionedObject> latest;
private String key;
public StackOfVersionedObjects(String key, final Object object) {
this.key = key;
VersionedObject vrObject = new VersionedObject(object);
latest = new Node<VersionedObject>(vrObject);
}
public boolean isEmpty() {
return latest == null;
}
// TODO: create a new version of the given object by pushing it to the top of the stack;
// the new versioned object should have the version of the latest object plus one;
// if the stack is empty, this method should throw an EmptyStackException
public void put(final Object object) throws EmptyStackException {
if (isEmpty())
throw new EmptyStackException();
Object tempObj = new Node();
Node tempNode = new Node();
latest.getNext(tempNode);
latest.setNext(temp); // I think??
// NO THIS DOESN'T WORK
} ...}
如果需要,这也是我的对象和节点类
对象等级:
public class VersionedObject {
private Object object;
private int version;
private static final int FIRST_VERSION = 0;
public VersionedObject(final Object object, int version) {
this.object = object;
if (version < FIRST_VERSION)
this.version = FIRST_VERSION;
else
this.version = version;
}
public VersionedObject(final Object value) {
this(value, FIRST_VERSION);
}
public Object getObject() {
return object;
}
public int getVersion() {
return version;
}
@Override
public String toString() {
return "VersionedObject{" +
"object=" + object +
", version=" + version +
'}';
}
}
节点类:
public class Node<T> {
private T data;
private Node next;
public Node() {
data = null;
next = null;
}
public Node(T data) {
this.data = data;
next = null;
}
public T getData() {
return data;
}
public Node<T> getNext() {
return next;
}
public void setData(T data) {
this.data = data;
}
public void setNext(Node<T> next) {
this.next = next;
}
@Override
public String toString() {
return data.toString();
}
}
解决方案
像这样更新您的put方法:
if (isEmpty())
throw new EmptyStackException();
int newVersion = latest.getData().getVersion() + 1;
VersionedObject vrObject = new VersionedObject(object,newVersion);
Node<VersionedObject> toAdd = new Node<>(vrObject);
toAdd.setNext(latest);
latest = toAdd;
推荐阅读
- sharepoint - Office 365、Sharepoint 和 One Drive 的图形 API 访问
- kotlin - 我的不可为空的 ArrayList 在调用它并抛出空指针异常时返回空值
- javascript - 参考错误:未定义数组值
- rpm - 一种在 rpmbuild 下执行外部脚本或获取 RPM_BUILD_ROOT 变量的方法
- virtual-machine - 从 bios 启用后 VT-x 无法工作。禁用它会显示 VT-x 可从英特尔标识中获得
- python - 将图像生成器与 GridSearchCV 配合使用
- python - 如何使用 matplotlib 在子图的 y 轴上截断非常长的刻度标签并在一个图中整齐地拟合图和标签?
- r - 仅对点着色并让 ggboxplot 中的方框图为黑色
- access-denied - SQLSTATE[HY000] [1045] 用户 'rentacar'@'localhost' 的访问被拒绝(使用密码:YES)
- python - 散点图矩阵