使用 c# 的基于数组的堆栈
Array-based Stack using c#
我已经实现了在基于数组的堆栈上实现 Push、Pop、Peek 的方法。但是我坚持使用 return 堆栈大小的方法并实现动态调整大小,因为我不明白 "dynamic resizing" 是什么。请帮忙!
动态调整大小意味着一旦堆栈已满,您就会增加堆栈。
growArray() 可以将当前容量翻倍,分配一个调整后大小的新数组,并将旧数组中的所有数据复制到新数组中。
首先,我想提一下您的程序存在的一些问题。
您真的要制作数组 public 吗?您不希望调用者直接修改数组。
在构造函数中,您应该确保容量不是负数。
您的一些属性可以只是字段。
容量只是数组的长度,应该是只读的。
private int[] data;
private int top;
private int Capacity { get { return data.Length; } }
Push 方法没有意义。如果数组已满,则只是取消推送操作。那就是你需要扩大数组的时候了。
public void Push(int value) {
if (IsFull()) GrowArray();
++top;
this.data[top] = value;
}
private void GrowArray() {
//determine what the new length should be
int newLength = Capacity == 0 ? 4 : Capacity * 2;
int[] newArray = new int[newLength];
//copy all the items to the new array.
for (int i = 0; i <= top ++i)
newArray[i] = data[i];
//instead of the for-loop you can write:
//Array.Copy(data, newArray, Capacity);
data = newArray; //replace the old array with the new
}
我已经实现了在基于数组的堆栈上实现 Push、Pop、Peek 的方法。但是我坚持使用 return 堆栈大小的方法并实现动态调整大小,因为我不明白 "dynamic resizing" 是什么。请帮忙!
动态调整大小意味着一旦堆栈已满,您就会增加堆栈。
growArray() 可以将当前容量翻倍,分配一个调整后大小的新数组,并将旧数组中的所有数据复制到新数组中。
首先,我想提一下您的程序存在的一些问题。
您真的要制作数组 public 吗?您不希望调用者直接修改数组。
在构造函数中,您应该确保容量不是负数。
您的一些属性可以只是字段。
容量只是数组的长度,应该是只读的。
private int[] data;
private int top;
private int Capacity { get { return data.Length; } }
Push 方法没有意义。如果数组已满,则只是取消推送操作。那就是你需要扩大数组的时候了。
public void Push(int value) {
if (IsFull()) GrowArray();
++top;
this.data[top] = value;
}
private void GrowArray() {
//determine what the new length should be
int newLength = Capacity == 0 ? 4 : Capacity * 2;
int[] newArray = new int[newLength];
//copy all the items to the new array.
for (int i = 0; i <= top ++i)
newArray[i] = data[i];
//instead of the for-loop you can write:
//Array.Copy(data, newArray, Capacity);
data = newArray; //replace the old array with the new
}