通过调整栈大小实现栈
Stack implementation by resizing the stack size
我正在尝试使用 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--];
}
我正在尝试使用 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--];
}