2015-04-02 98 views
0

我已经实现的方法,以实现压入,弹出,PEEK上基于阵列的堆栈。但我坚持的方法来返回堆栈的大小和实现动态调整大小,因为我不明白什么是“动态调整大小”是。请帮忙!基于阵列的堆栈使用C#

+0

什么错框架中的堆栈? https://msdn.microsoft.com/en-us/library/3278tedw%28v=vs.110%29.aspx – Jodrell 2015-04-02 14:23:11

回答

0

首先,我想提一些事情是错了你的计划。
你真的想让阵列公开吗?你不希望调用者直接修改数组。
在构造函数中,您应该确保容量不是负数。
你的一些属性可以只是字段。
容量只是数组的长度,它应该是只读的。

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 
} 
+0

而不是for循环,你可以写'Array.copy(data,newArray,Capacity);' – wiseveri 2015-04-02 13:58:24

+0

@wiseveri检查! – 2015-04-02 14:03:18

+0

非常感谢您的帮助:) – 2015-04-02 14:05:13

0

动态调整大小意味着你长大堆栈一旦它的全部。

growArray()可以只加倍的电流容量,以所调整的大小分配一个新的数组,并从旧的阵列复制所有数据到新的一个。

+0

我现在明白了。但不知道如何实现它:-ss – 2015-04-02 13:28:47

+0

@Dennis_E确实为您提供了一个实现。 – wiseveri 2015-04-02 13:57:27