# Data Structures: Stackself.__wrap_n!=1&&self.__wrap_b(":Rdttt9da:",1)

- 0 views

Stack is a linear data structure where the elements follow a First In Last Out (FILO) order. It can also be thought as Last In First Out. Stacks can be used for things like tracking which functions are currently running and the navigation state in a web app.

## Implementing a Stack data structure

Even though we will be implementing the Stack data structure in TypeScript in this example, the basic concept can be implemented in any language.

First declare a class.

``class Stack<T> {}``

Then declare a private member variable array to store the data of the stack. Making it private will stop it from being directly accessed from outside the class.

``````class Stack<T> {
private _data: T[] = [];
}``````

Next, we need a way to check the size of the stack. We can use a getter to access the size of the `_data` array.

``````class Stack<T> {
private _data: T[] = [];

// Check the size of the stack
get size(): number {
return this._data.length;
}
}``````

After that we’ll add a method to check whether the stack is empty or not.

``````class Stack<T> {
private _data: T[] = [];

// Check the size of the stack
get size(): number {
return this._data.length;
}

// Returns whether the stack is empty or not
public isEmpty(): boolean {
return this._data.length === 0;
}
}``````

Now we need a method to add new elements to the stack. We can use the `push()` method in arrays to add an element to the end of the `_data` array.

``````class Stack<T> {
private _data: T[] = [];

// Check the size of the stack
get size(): number {
return this._data.length;
}

// Returns whether the stack is empty or not
public isEmpty(): boolean {
return this._data.length === 0;
}

// Adds an element to the top of the stack
public push(element: T): T {
this._data.push(element);

return element;
}
}``````

Finally we will implement two methods to check the element on top of the stack. One will just check the value, `peek()`, and the other will remove the element from the stack and return it, `pop()`. Both will throw an error if they are called when the stack is empty, i.e. the length of the `_data` array is zero.

``````class Stack<T> {
private _data: T[] = [];

// Check the size of the stack
get size(): number {
return this._data.length;
}

// Returns whether the stack is empty or not
public isEmpty(): boolean {
return this._data.length === 0;
}

// Adds an element to the top of the stack
public push(element: T): T {
this._data.push(element);

return element;
}

// Returns the value of the element on top of the stack without removing it
public peek(): T {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}

return this._data[this._data.length - 1];
}

// Removes the topmost element of the stack and returns it
public pop(): T {
if (this.isEmpty()) {
throw new Error("Stack is empty");
}

return this._data.pop() as T;
}
}``````

Below is an example on how to use the Stack class we just created. The stack can be created to hold any type of data.

``````const numberStack: Stack<number> = new Stack<number>();

console.log(numberStack.isEmpty()); // true
console.log(numberStack.size); // 0

numberStack.push(1);
// 1
numberStack.push(2);
// 1, 2
numberStack.push(3);
// 1, 2, 3

console.log(numberStack.isEmpty()); // false
console.log(numberStack.size); // 3

console.log(numberStack.peek()); // 3
console.log(numberStack.pop()); // 3
console.log(numberStack.pop()); // 2
console.log(numberStack.pop()); // 1

console.log(numberStack.isEmpty()); // true
console.log(numberStack.size); // 0``````
0
{"ft_lang_label":"__label__en","ft_lang_prob":0.5556173,"math_prob":0.9532108,"size":3410,"snap":"2023-40-2023-50","text_gpt3_token_len":833,"char_repetition_ratio":0.17615972,"word_repetition_ratio":0.35852373,"special_character_ratio":0.28651026,"punctuation_ratio":0.18439716,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9901241,"pos_list":[0,1,2],"im_url_duplicate_count":[null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-11-29T18:13:58Z\",\"WARC-Record-ID\":\"<urn:uuid:3d7a69aa-eabe-4034-8ec3-a8885e32886a>\",\"Content-Length\":\"112129\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1c31b05e-9933-439b-98b0-4e0085119005>\",\"WARC-Concurrent-To\":\"<urn:uuid:8b073a2c-635f-4e3c-a6cb-e79ed529562d>\",\"WARC-IP-Address\":\"76.76.21.93\",\"WARC-Target-URI\":\"https://akhilaariyachandra.com/blog/data-structures-stack\",\"WARC-Payload-Digest\":\"sha1:ZTTZIIYP4MYHPEPXVF77INLY35ZEB62U\",\"WARC-Block-Digest\":\"sha1:YCPU33BC5AGSBTXGHFMTO2CK2YF6GKVO\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100135.11_warc_CC-MAIN-20231129173017-20231129203017-00828.warc.gz\"}"}