用数组实现可以动态扩容的栈,详细代码如下:
package stack;
public class StackByArrayAutoCapacity {
String[] arrays;
int autoCapacity;
int count;
int index;
public StackByArrayAutoCapacity(int n) {
arrays = new String[n];
autoCapacity = n;
count = n;
index = 0;
}
public boolean push(String item) {
if (index == count) {
String[] temp = arrays;
arrays = new String[count + autoCapacity];
for (int i =0;i<temp.length;i++) {
arrays[i] = temp[i];
}
count = count + autoCapacity;
}
arrays[index] = item;
index++;
return true;
}
public String pop() {
if (index == 0) {
return null;
}
String temp = arrays[index - 1];
index--;
return temp;
}
public String peek() {
if (index == 0) {
return null;
}
String temp = arrays[index - 1];
return temp;
}
public boolean empty() {
return index == 0;
}
}
复杂度分析
时间复杂度 : push 和 pop 均为:O(1)
空间复杂度 : push 和 pop 均为:O(1)
网友评论