[英]Write a push method for a dynamic stack linked list java
在尝试编写一个本质上推入动态堆栈的方法时,我遇到了一些麻烦。 我不完全确定如何编写它,所以我想知道是否有人对如何推进这个有任何指示或提示。
这是 class 的一部分
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
} ...}
这是我的 object 和节点 class 以及如果需要的话
Object Class:
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 +
'}';
}
}
节点 Class:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.