📄 stackofintegers.java
字号:
/**
* @(#)StackOfIntegers.java
*
*
* @author
* @version 1.00 2009/3/18
*/
public class StackOfIntegers {
private int[] elements;
/**这里注意数组下标从0开始,
*而size表示栈(数组)中元素的个数,
*因此栈顶的元素为elements[size-1]
*/
private int size=0;
/*Construct a stack with the default capacity 16*/
public StackOfIntegers() {
this(16);
}
/*Construct a stack with the specified maximum capacity*/
public StackOfIntegers(int capacity)
{
elements=new int[capacity];
}
/**Push a new integer into the top of the stack*/
public int push(int value)
{
//If the stack is full,create a new one of double capacity and copy elements into the new one.
if(size>=elements.length)
{
int[]temp=new int [elements.length*2];
System.arraycopy(elements,0,temp,0,elements.length);
elements=temp;
}
//Push the value into the stack
/*size先赋值,再自增*/
return elements[size++]=value;
}
/**Return and remove the top element from the stack*/
public int pop()
{
return elements[--size];
}
/**Return the top elements from the stack*/
public int peek()
{
return elements[size-1];
}
/**Test whether the stack is empty*/
public boolean empty()
{
return size==0;
}
/**Return the number of the elements in the stack*/
public int getSize()
{
return size;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -