题目地址:
https://www.lintcode.com/problem/implement-stack/description
实现栈。
可以用一个数组实现栈,另外用一个变量size
来标记当前栈里元素个数。如果在push的时候size = stack.length
了,则需要扩容,一般扩容成两倍。如果pop后size = stack.length / 4
,则栈可以缩容成stack.length / 2
以防复杂度震荡。代码如下:
public class Stack {
int[] stack = new int[10];
int size = 0;
/*
* @param x: An integer
* @return: nothing
*/
public void push(int x) {
// write your code here
if (size == stack.length) {
resize(stack.length * 2);
}
stack[size++] = x;
}
/*
* @return: nothing
*/
public void pop() {
// write your code here
size--;
if (size == stack.length / 4 && stack.length / 4 > 0) {
resize(stack.length / 2);
}
}
/*
* @return: An integer
*/
public int top() {
// write your code here
return stack[size - 1];
}
/*
* @return: True if the stack is empty
*/
public boolean isEmpty() {
// write your code here
return size == 0;
}
private void resize(int newCapacity) {
int[] tmp = new int[newCapacity];
for (int i = 0; i < size; i++) {
tmp[i] = stack[i];
}
stack = tmp;
}
}
所有操作复杂度和普通栈一样。