我在 JAVA 中动态地实现了一个 Stack,我遇到了这个问题。问题是,我的代码有效,但我不知道为什么。所以这是我不明白的部分代码:
Node<E> newNode = new Node(elem,top);
newNode=top;
size++;
所以,我的 newNode 的第二个参数是它旁边的对象,在这种情况下是顶部的。然后我说我的 newNode=top; 所以,按照我的逻辑,newNode 在 newNode 旁边,因为我在之后的指令中说过 newNode = top; 我在这里想念什么?我知道这是一个愚蠢的问题 :( 问题是,它有效,我已经看到了一些类似的实现,我只是不明白它为什么有效。
编辑:生病发布我的整个代码:
类节点:
public class Node<E> {
private E element;
private Node<E> next;
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
//到此结束
接口栈:
public interface Stack<E> {
//numero de elementos presentes na pilha
public int size( );
//nao contem elementos?
public boolean isEmpty( );
//devolve proximo objecto a sair, sem remover
public E peek( )
throws EmptyStackException;
//empilha novo elemento
public void push(E o)
throws FullStackException;
//desempilha proximo elemento
public E pop()
throws EmptyStackException;
}
//界面到此结束
类 StackDynamic
public class StackDynamic<E> implements Stack<E>{
private int size;
private Node<E> top;
private int maxCapacity;
public StackDynamic(int capacity)
{
this.maxCapacity=capacity;
this.size=0;
this.top=null;
}
public StackDynamic()
{
this(-1);
}
@Override
public int size() {
return this.size;
}
@Override
public boolean isEmpty() {
return (this.size == 0);
}
@Override
public E peek() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("A pilha está vazia.");
}
return top.getElement();
}
@Override
public void push(E elem) throws FullStackException {
if(size==maxCapacity){
throw new FullStackException("Está cheio");
}
**Node<E> newNode = new Node<>(elem, top);
top=newNode;
size++;** //error here
}
@Override
public E pop() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("A pilha está vazia.");
}
E elemRemoved = top.getElement();
top = top.getNext();
size--;
return elemRemoved;
}
//类到此结束
现在 newNode=top; 命令对我来说没有多大意义:S