c语言 数组扩容,数组的扩容
用數組模擬棧
數組是固定大小的,不能改變長度,要想達到數組擴容的目的,就只能把當前數組復制到一個更長長度的數組中;
使用Arrays.copyOf()方法
源碼如下:
public static short[] copyOf(short[] original, int newLength) {
short[] copy = new short[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
可以看出,內部調用了System.arraycopy()方法。
下面是用數組實現一個棧的代碼:
class MinStack {
/** initialize your data structure here. */
int[] stack ;//數組
int defaultSize = 2;//默認大小
int realNumber;//存在的數量
public MinStack() {
this.stack = new int[defaultSize];
}
public void push(int x) {
if(realNumber == stack.length){
stack = Arrays.copyOf(stack,stack.length+defaultSize);
}
stack[realNumber++] = x;
}
public void pop() {
if(realNumber > 0){
realNumber--;
}
}
public int top() {
return stack[realNumber-1];
}
public int getMin() {
int min = stack[0];
for(int i = 0;i < realNumber;i++){
if(min > stack[i]){
min = stack[i];
}
}
return min;
}
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的c语言 数组扩容,数组的扩容的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .net中的mapinfo开发:准备(一
- 下一篇: pcfg 自然语言处理_自然语言处理:原