我正在尝试使用数组和字符串缓冲区来实现堆栈。让我困惑的是如何正确确定字符串的大小而不聚集字符串中的数组元素。增长应该使我的缓冲区的容量加倍(我尝试使用 Ensurecapacity 来实现)。对于转换,我将数组中的元素附加到缓冲区,但正如已经提到的,现在知道如何在不丢失数组元素的真正含义的情况下执行此操作。
public class Stack {
private int[] buffer;
private int size;
public Stack(int capacity) {
//TODO
buffer = new int [capacity];
size =0;
}
public String toString() {
StringBuffer converter = new StringBuffer(); //initializing buffer
int i=0; //
while(i<=size) { //while loop let's us append the elements of the array into our stringbuffer
converter.append(buffer[i]+ " ");
}
String wanted = converter.toString(); //converting the buffer to a string
return wanted;
}
private void grow() {
//TODO
StringBuffer doubler = new StringBuffer();
doubler.append(toString()); //adding our string into the new buffer
int l = doubler.length();
doubler.ensureCapacity(l-1); //ensure capacity(if the min argument is smaller than the actual capacity)
} //will take 2*min arg +2 as new capacity
}
弑天下
凤凰求蛊
相关分类