棧與隊列(Stack and Queue)

1.定義

  

  棧:後進先出(LIFO-last in first out):最後插入的元素最早出來。前端

  隊列:先進先出(FIFO-first in first out):最早插入的元素最早出來。算法

2.用數組實現棧和隊列

實現棧:

  因爲數組大小未知,若是每次插入元素都擴展一次數據(每次擴展都意味着構建一個新數組,而後把舊數組複製給新數組),那麼性能消耗至關嚴重。數組

  這裏使用貪心算法,數組每次被填滿後,加入下一個元素時,把數組拓展成現有數組的兩倍大小。ide

  每次移除元素時,檢測數組空餘空間有多少。當數組裏的元素個數只有整個數組大小的四分之一時,數組減半。性能

  爲何不是當數組裏的元素個數只有整個數組大小的二分之一時,數組減半?考慮如下狀況:數組有4個元素,數組大小爲4個元素空間。此時,加一個元素,數組拓展成8個空間;再減一個元素,數組縮小爲4個空間;如此循環,性能消耗嚴重。測試

  具體代碼(Java):this

  

public ResizingArrayStackOfStrings()
{
    s=new String[1];
int N = 0; } pubilc
void Push(String item) { //若是下一個加入元素超出數組容量,拓展數組 if(N == s.length) Resize(2 * s.length); s[N++] = item; } private void Resize(int capacity) { String[] copy = new String[capacity]; //將舊數組元素複製給新數組 for(int i=0; i<N; i++) copy[i] = s[i]; s = copy; } public String Pop() { String item = s[--N]; s[N] = null; //剩餘元素只佔數組四分之一空間時,數組減半 if(N>0 && N=s.length/4) Resize(s.length/2); return item; }

效果以下圖:spa

 實現隊列

  與棧相似:3d

       數組每次被填滿後,加入下一個元素時,把數組拓展成現有數組的兩倍大小。code

  每次移除元素時,檢測數組空餘空間有多少。當數組裏的元素個數只有整個數組大小的四分之一時,數組減半。

  不一樣之處在於:

       因爲是先進先出,移除是從隊列的最前端開始的。因此當咱們移除數個數據後,隊列數據是存儲在數組的中間部分的。令隊列數據的尾端數據ID爲Num,首端數據ID爲HeadIndex,則Num - HeadIndex爲隊列數據元素個數。

       當隊列數據元素個數爲整個數組空間的四分之一時,數組減半,且隊列數據左移至數組最左端。即Num-=HeadIndex;HeadIndex=0;

  圖中,HeadIndex=2;Num=5;

 

具體代碼:

.h:

UCLASS()
class ALGORITHM_API AStackAndQueuesExerciseTwo : public AActor
{
    GENERATED_BODY()
    
public:    
    // Sets default values for this actor's properties
    AStackAndQueuesExerciseTwo();
    // Called every frame
    virtual void Tick(float DeltaTime) override;
    //輸入
    void Enqueue(int Input);
    //重構數組(拓展或縮小)
    void Resize(int Capacity);
    //輸出且移除
    int Dequeue();
    //隊列裏沒元素了?
    bool IsEmpty();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:    
    
private:
    //記錄數組中有多少個Int
    int Num;
    //隊列數組
    TArray<int> MyIntArray;
    //記錄下一個移除的數據ID
    int HeadIndex;
};

.cpp:

AStackAndQueuesExerciseTwo::AStackAndQueuesExerciseTwo()
{
     // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;
    //一開始數組沒成員
    Num = 0;
    HeadIndex = 0;
    //數組中有一個假元素
    MyIntArray.Add(0);
}

// Called when the game starts or when spawned
void AStackAndQueuesExerciseTwo::BeginPlay()
{
    Super::BeginPlay();
    //測試
    Enqueue(1);
    Enqueue(2);
    Enqueue(3);
    Enqueue(4);
    Enqueue(5);
    Dequeue();
    Dequeue();
    Dequeue();
    //隊列數組成員
    for (int i = HeadIndex; i < Num; i++)
    {
        UKismetSystemLibrary::PrintString(this, "i: " + FString::FromInt(i) + " End: " + FString::FromInt(MyIntArray[i]));
    }
    //隊列數組的容量
    UKismetSystemLibrary::PrintString(this, "MyIntArray.Num(): " + FString::FromInt(MyIntArray.Num()));
}

// Called every frame
void AStackAndQueuesExerciseTwo::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

void AStackAndQueuesExerciseTwo::Enqueue(int Input)
{
    //若是隊列數組已滿,拓展數組
    if (Num == MyIntArray.Num())
    {
        Resize(2 * MyIntArray.Num());
    }
    //拓展或者數組有空位時,添加元素
    if (Num < MyIntArray.Num())
    {
        MyIntArray[Num] = Input;
    }
    Num++;
}


void AStackAndQueuesExerciseTwo::Resize(const int Capacity)
{
    //int a[] = new int[Capacity];
    TArray<int> Copy;
    //添加數個假元素填充數組
    for (int i = 0; i < Capacity; i++)
    {
        Copy.Add(0);
    }
    //將隊列數組賦值給Copy數組,若是是縮小數組,則把隊列數組左移,節省空間
    for (int i = HeadIndex; i < Num; i++)
    {
        Copy[i - HeadIndex] = MyIntArray[i];
    }
    MyIntArray = Copy;
}

int AStackAndQueuesExerciseTwo::Dequeue()
{
    //判斷數組是否爲空
    if (IsEmpty())
    {
        UKismetSystemLibrary::PrintString(this, "No Element Exist!!!");
        return 0;
    }
    else
    {
        UKismetSystemLibrary::PrintString(this, "Dequeue: " + FString::FromInt(MyIntArray[HeadIndex]));
    }
    HeadIndex++;
    //若是移除元素後,所剩元素爲數組空間的四分之一,則數組減半
    if ((Num - HeadIndex) != 0 && (Num - HeadIndex) == (MyIntArray.Num() / 4))
    {
        Resize(MyIntArray.Num() / 2);
        //移除空間後,隊列數組左移,節省空間
        Num -= HeadIndex;
        HeadIndex = 0;
        return MyIntArray[HeadIndex];
    }
    else
    {
        return MyIntArray[HeadIndex - 1];
    }
    
}
//若是下一個要移除的數據不存在,則爲空數組
bool AStackAndQueuesExerciseTwo::IsEmpty()
{
    return HeadIndex >= Num;
}
相關文章
相關標籤/搜索