如何在 TypeScript 中使用陣列建立棧?


棧是一種基於 LIFO(後進先出)的資料結構。簡而言之,這意味著最後新增到棧中的元素將首先從棧中彈出。

使用者可以在棧上執行一些基本操作。例如,我們可以將元素推入棧中,從棧中彈出元素,或者檢視棧頂元素。

在這裡,使用者可以看到棧的基本方法,我們也將在本教程中建立棧時實現這些方法。

棧方法

  • Push() − 允許我們將元素新增到棧中。

  • Pop() − 允許從棧中移除最後一個元素。

  • Peek() − 返回棧頂元素,但不將其移除。

  • isEmpty() − 根據棧是否為空返回布林值。

  • isFull() − 根據棧是否已滿返回 true 或 false 值。

  • Size() − size() 方法返回表示棧大小的數值。

  • printStack() − printStack() 方法列印所有棧的值。

實現棧類

現在,我們將使用 TypeScript 中的類和介面來實現一個棧。使用者可以按照以下步驟建立棧。

步驟 1 − 建立一個包含所有棧方法的介面。

interface stackInterface<dataType> {
   push(dataItem: dataType): void;
   pop(): dataType | null | undefined;
   peek(): dataType | null;
   isEmpty(): boolean;
   isFull(): boolean;
   size(): number;
   printStack(): void;
}

在上面的程式碼中,使用者可以看到我們已經聲明瞭名為 stackInterface 的介面中所有棧方法及其引數和返回型別。我們將在棧類中實現上述介面。

步驟 2 − 現在,我們需要建立一個 StackClass 並定義上述介面中宣告的所有方法。此外,建立私有成員 data 和 stackSize 分別用於儲存棧元素和棧的最大大小。

步驟 3 − 之後,建立一個建構函式來初始化棧的最大大小,如下所示。

constructor(size: number) {
   this.stackSize = size;
}

步驟 4 − 現在,我們需要為棧實現 push() 方法。

push(dataItem: dataType): void {
   if (this.data.length === this.stackSize) {
      // throw error
   }
   this.data.push(dataItem);
}

在上面的程式碼中,我們檢查棧是否已滿。如果棧已滿,則丟擲錯誤;否則,使用 Array.push() 方法將元素推入陣列。

步驟 5 − 接下來,為棧實現 pop() 方法。

pop(): dataType | null | undefined {
   return this.data.pop();
}

在上面的程式碼中,我們使用 Array.pop() 方法從陣列的最後一個索引移除元素。

步驟 6 − 接下來,在 StackClass 中實現 peek() 方法。

peek(): dataType | null {
   return this.data[this.size() - 1];
}

在上面的程式碼中,我們訪問陣列的最後一個元素並將其返回。

步驟 7 − 為 StackClass 實現 isEmpty() 方法。

isEmpty(): boolean {
   return this.data.length <= 0;
}

我們使用陣列的 length 方法來檢查棧是否為空。

步驟 8 − 使用者可以按照以下語法定義 isFull() 方法。

isFull(): boolean {
   let result = this.data.length >= this.stackSize;
   return result;
}

我們將陣列的長度和 stackSize 屬性的值進行比較,以檢查棧是否已滿。

步驟 9 − 使用者可以使用以下程式碼為 StackClass 實現 size() 方法。

size(): number {
   return this.data.length;
}

棧的大小類似於陣列的大小,要獲取陣列的大小,我們可以使用 length 屬性。

步驟 10 − 接下來,定義 printStack() 方法來列印棧的元素。

printStack(): void {
    
   this.data.forEach((dataItem) => {
      // print dataItem
   });
}

在上面的程式碼中,我們遍歷 data 陣列並列印所有陣列值。

示例

在下面的示例中,我們建立了 StackClass,它實現了 stackInterface。此外,使用者還可以看到如何使用自定義資料型別建立棧。

下面的示例 StackClass 包含所有上述方法的實現。之後,我們建立了 StackClass 的物件並使用數字作為資料型別。之後,我們使用了 StackClass 的各種方法來對棧執行不同的操作。

interface stackInterface<dataType> {
   push(dataItem: dataType): void;
   pop(): dataType | null | undefined;
   peek(): dataType | null;
   isEmpty(): boolean;
   isFull(): boolean;
   size(): number;
   printStack(): void;
}

class StackClass<dataType> implements stackInterface<dataType> {
   private data: Array<dataType> = [];
   private stackSize: number = 0;

   constructor(size: number) {
      this.stackSize = size;
   }

   push(dataItem: dataType): void {
      if (this.data.length === this.stackSize) {
         throw Error(
            "You can't add more elements to stack as stack storage is full!"
         );
      }
      this.data.push(dataItem);
   }

   pop(): dataType | null | undefined {
      let element = this.data.pop();
      return element;
   }

   peek(): dataType | null {
      let element = this.data[this.size() - 1];
      return element;
   }
   isEmpty(): boolean {
      let result = this.data.length <= 0;
      return result;
   }
   isFull(): boolean {
      let result = this.data.length >= this.stackSize;
      return result;
   }
   size(): number {
      let len = this.data.length;
      return len;
   }
   printStack(): void {
      console.log("All stack values are printed below!");
      this.data.forEach((dataItem) => {
         console.log(dataItem);
      });
   }
}

const newstack = new StackClass<number>(5);
newstack.push(10);
newstack.push(12);
newstack.push(897);
newstack.push(54);
newstack.push(14);

console.log("The peek element of the stack is " + newstack.peek());
console.log("Is stack full? " + newstack.isFull());
console.log("The last removed element from the stack is " + newstack.pop());
console.log("The size of the stack is " + newstack.size());
console.log("Is stack empty? " + newstack.isEmpty());
newstack.printStack();

編譯後,將生成以下 JavaScript 程式碼:

var StackClass = /** @class */ (function () {
   function StackClass(size) {
      this.data = [];
      this.stackSize = 0;
      this.stackSize = size;
   }
   StackClass.prototype.push = function (dataItem) {
      if (this.data.length === this.stackSize) {
         throw Error("You can't add more elements to stack as stack storage is full!");
      }
      this.data.push(dataItem);
   };
   StackClass.prototype.pop = function () {
      var element = this.data.pop();
      return element;
   };
   StackClass.prototype.peek = function () {
      var element = this.data[this.size() - 1];
      return element;
   };
   StackClass.prototype.isEmpty = function () {
      var result = this.data.length <= 0;
      return result;
   };
   StackClass.prototype.isFull = function () {
      var result = this.data.length >= this.stackSize;
      return result;
   };
   StackClass.prototype.size = function () {
      var len = this.data.length;
      return len;
   };
   StackClass.prototype.printStack = function () {
      console.log("All stack values are printed below!");
      this.data.forEach(function (dataItem) {
         console.log(dataItem);
      });
   };
   return StackClass;
}());
var newstack = new StackClass(5);
newstack.push(10);
newstack.push(12);
newstack.push(897);
newstack.push(54);
newstack.push(14);
console.log("The peek element of the stack is " + newstack.peek());
console.log("Is stack full? " + newstack.isFull());
console.log("The last removed element from the stack is " + newstack.pop());
console.log("The size of the stack is " + newstack.size());
console.log("Is stack empty? " + newstack.isEmpty());
newstack.printStack();

輸出

上述程式碼將產生以下輸出:

The peek element of the stack is 14
Is stack full? true
The last removed element from the stack is 14
The size of the stack is 4
Is stack empty? false
All stack values are printed below!
10
12
897
54

在本教程中,我們學習瞭如何從頭開始建立棧。我們已經從頭開始實現了棧的各種方法。此外,使用者可以建立任何資料型別的棧。甚至使用者可以建立“any”資料型別的棧並新增多種資料型別的元素。

更新於:2023年1月20日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.