STACKS

Stacks

A stack is a data structure that has way more limitations, compared to arrays. We can add items to a stack only by adding them on top. And we can only remove the item on top of the stack.

The order in which elements come off a stack gives rise to its alternative name, LIFO (last in, first out).

Stacks

Implementing a Stack in JavaScript

  1. Push () → Add an element to the stack.
  2. Pop () → Delete an element from the stack.
  3. Peek () → Get the top element of the stack.
  4. Length () → Return the length of the stack.
  5. Search () → Search for the element in the stack.
  6. IsEmpty () → Check if the stack is empty.
  7. Print () → Print the elements of the stack.
const stack = [1,2,3,4];
stack.push(5);
// [1,2,3,4,5]
stack.pop();
// -> 5
// [1,2,3,4]

Example :

let letters = [];
let word = "racecar";
let reverseword = "";
// put letters of words in to stack
for (let i = 0; i < word.length; i++) {
letters.push(word[i]);
}
console.log(letters);
// pop off the stack in reverse order
for (let i = 0; i < word.length; i++) {
reverseword += letters.pop();
}
console.log(reverseword);
if (reverseword === word) {
console.log(word + "is a palindrome");
} else {
console.log(word + "is not a palindrome");
}
//output: racecar is a palindrome