data-structures - 通过调整堆栈大小来实现堆栈
问题描述
我试图使用 java 来实现一个堆栈,并调整堆栈大小。我的代码是正确的并且运行良好,但是当我再次调用 peek 函数时从堆栈中弹出元素后,相同的元素显示在堆栈顶部。显示我应该进行哪些更改以使我的代码正确。
class DynamicStack
{
private int stack[];
private int stackSize;
private int top ;
DynamicStack()
{
stackSize = 1;
top = -1;
stack = new int[stackSize];
}
public int isEmpty()
{
if(top == -1)
{
System.out.println("Stack is empty");
}
return 0 ;
}
public int isFull()
{
if(top == stackSize-1)
{
System.out.println("Stack is full");
}
return 0;
}
public int pop()
{
return stack[top];
}
public void push(int data)
{
if(top>=stackSize-1)
resize();
stack[++top]=data;
}
private void resize()
{
int[] temp= stack;
stackSize = stackSize*2;
stack = new int[stackSize];
for(int i= 0;i<=top;i++)
{
stack[i]=temp[i];
}
}
public int peek()
{
return stack[top];
}
public static void main(String[] args)
{
DynamicStack ds = new DynamicStack();
ds.push(12);
ds.push(13);
ds.push(2);
System.out.println(ds.stackSize);
System.out.println(ds.peek());
System.out.println(ds.pop());
System.out.println(ds.peek());
}
}
解决方案
top
您应该像推送到堆栈时一样更新您的变量。
public int pop()
{
return stack[top--];
}
推荐阅读
- javascript - 在弹出确认对话框之前做一些事情
- java - 从最小堆中添加或删除元素
- xcode - 使 Xcode 自定义输出“可点击”到代码行
- containers - 使用容器创建的 Google 计算引擎实例执行多次而不是一次
- php - 如何将 PDOStatement 转换为 JSON 并打印出来?
- ios - 无法使用类型为“([String:Any],完成:((错误?)-> Void)?)”的参数列表调用“setData”
- firebase - firebase 仪表板不显示 admob 收入
- javascript - 凯撒密码转换javascript的问题
- c++ - 使用 mysql 连接构建 C++ 程序
- java - 发送不必要的对象有多大影响?