node == null 如何检查堆栈是否已满?

问题描述

如果我们创建的新节点是空的(什么都没有),它怎么不把栈引用为空而是检查栈是否已满?

 //push() function

public void push(int x) {
    
    //create a new node and allocate memory
    Node node = new Node();

    //check if the stack is full i.e check for stack overflow
    if(node == null) {
        System.out.println("\n Stack is full. Stack Overflow!");
        return;
    }
    node.data = x;
    node.next = head;
    head = node;
}

//check for an empty stack
public boolean isEmpty() { 
    return head == null;
}

解决方法

简单地说,你引用的代码不是很好。 :-)

如评论中所述,您在此处发布的 Java 代码永远无法通过 if 检查,因为如果进行分配时没有内存,则代码将生成 OutOfMemoryError 而不是而不是将引用留空。链接的 C++ 代码也不能有 if 语句触发器,因为在 C++ 中,如果 new 内存不足,它将抛出 std::bad_alloc 异常。