1. 程式人生 > >演算法學習(一)揹包佇列和棧(優化)

演算法學習(一)揹包佇列和棧(優化)

以棧為例,之前是增加一個元素就要重新new一個比原來大1的陣列出來替換原始陣列。

public void Push(T item)
{
    int size = Size();
    T[] newarray = new T[size + 1];
    for (int i = 0; i < size; i++)
    {
        newarray[i] = array[i];
    }
    newarray[size] = item;
    this.array = newarray;
}

將stack類進行修改優化,減少了重複定義的次數,提高了入棧出棧效率

public class My_Stack<T>
{
    public My_Stack()
    {
        Max_Capacity = 8;
        array = new T[Max_Capacity];
        actual_size = 0;
    }
    private T[] array;
    private int Max_Capacity;
    private int actual_size;
    /// <summary>
    /// 入棧
    /// </summary>
    /// <param name="item"></param>
public void Push(T item) { if (actual_size > Max_Capacity / 2) { //翻倍 Max_Capacity *= 2; T[] newarray = new T[Max_Capacity]; for (int i = 0; i < actual_size; i++) { newarray[i] = array[i]; }
newarray[actual_size] = item; this.array = newarray; } else { array[actual_size] = item; } actual_size += 1; } /// <summary> /// 出棧 /// </summary> /// <param name="item"></param> public T Back() { if (Size() == 0) { Console.WriteLine("未新增元素"); return default(T); } else { T num = array[actual_size - 1]; array[actual_size - 1] = default(T); actual_size -= 1; return num; } } /// <summary> /// 刪除後進的一個元素 /// </summary> public void Pop() { if (Size() == 0) { Console.WriteLine("未新增元素"); } else { array[actual_size - 1] = default(T); actual_size -= 1; } } /// <summary> /// 判斷是否為空 /// </summary> /// <returns></returns> public bool Isempty() { if (actual_size == 0) { return true; } else { return false; } } /// <summary> /// 獲取大小的方法 /// </summary> /// <returns></returns> public int Size() { if (array == null) { return 0; } else { return actual_size; } } /// <summary> /// 獲取佇列長度的屬性 /// </summary> public int Length { get { return Size(); } } /// <summary> /// 理論最大容量 /// </summary> public int MaxCapacity { get { return Max_Capacity; } } }