Stack
Description:
The stack is a data structure for lists that follows the Last In - First Out (LIFO) rule. The last elements that enter the list, or the staclk, is the first elements that is going to get out of it.
You can see this as a t-shirts pile, when you store your t-shirts on the closet you put one in top of the other. When you want to get a t-shirt, the first that you are going to get is the last one that you put on top.
Implementation:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Define a new stack.
const stack = () => {
// Define the data of the stack.
let data: any[] = [];
return {
// Add elements to the end of the stack.
push: (element: any) => {
data = [element, ...data];
},
// Get the first element to enter the stack.
pop: (): any => {
const elementToPop = data[0];
data = data.slice(1, data.length);
return elementToPop;
},
// Get the element that is in the first position of the stack.
first: (): any => {
return data[0];
},
// Get all the elments of the stack.
list: (): any[] => {
return data;
}
}
};
Testing it
So, we are going to test in console to see if it is working. We are going to run the following:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Creates a new stack
console.log('** Creates a new stack.');
const newStack = stack();
// Add a elements to the stack.
console.log('** Push elements to the stack.');
newStack.push({item: "A"});
// Stack data after pushing.
console.log('** Stack elements: ', newStack.list().map(element => element.item).join(','));
newStack.push({item: "B"});
// Stack data after pushing.
console.log('** Stack elements: ', newStack.list().map(element => element.item).join(','));
newStack.push({item: "C"});
// Stack data after pushing.
console.log('** Stack elements: ', newStack.list().map(element => element.item).join(','));
newStack.push({item: "D"});
// Stack data after pushing.
console.log('** Stack elements: ', newStack.list().map(element => element.item).join(','));
// Get the first element
console.log('** Pop the first element.');
const firstElement = newStack.pop();
console.log('firstElement: ', firstElement.item);
// Stack data after pop.
console.log('** Stack elements: ', newStack.list().map(element => element.item).join(','));
// Add that element back to the stack.
console.log('** Add that element back to the stack.');
newStack.push(firstElement);
// Final stack.
console.log('** Final stack elements: ', newStack.list().map(element => element.item).join(','));
You should see something like the following in the console:
0
1
2
3
4
5
6
7
8
9
10
11
** Creates a new stack.
** Push elements to the stack.
** Stack elements: A
** Stack elements: B,A
** Stack elements: C,B,A
** Stack elements: D,C,B,A
** Pop the first element.
firstElement: D
** Stack elements: C,B,A
** Add that element back to the stack.
** Final stack elements: D,C,B,A