Skip to content

Instantly share code, notes, and snippets.

@aungmyatmoethegreat
Last active June 22, 2021 13:23
Show Gist options
  • Save aungmyatmoethegreat/df63798348e81964f044d6fb62cc964a to your computer and use it in GitHub Desktop.
Save aungmyatmoethegreat/df63798348e81964f044d6fb62cc964a to your computer and use it in GitHub Desktop.
Last In Fast Out Algorithm (Stack Memory)
// stack memory
let stack = [];
// top pointer
let top = 0;
// maximum length of stack
let max_length = 5;
// insert data to the stack
const push = (element) => {
// check the stack is full or no5
if (stack.length >= max_length) {
throw new Error('Stack Overflow Error Occured');
}
// insert data to the empty of stack
stack[top] = element;
// take new empty space for next data
top = top + 1;
console.log('Data Inserted');
};
// remove the data
const pop = () => {
// check stack is empty or not
if (empty()) {
throw new Error('Empty Stack');
}
top = top - 1;
stack.pop();
console.log('Data Removed');
};
// access the element that is on the top of stack
const peek = () => stack[top - 1];
// check the length of stack
const empty = () => !stack.length;
// print all data of stack
const print = () => {
while (top > 0) {
console.log(peek());
top--;
}
};
try {
// set data
push(1);
push(2);
push(3);
push(4);
push(5);
// print all data to console
print();
}catch(e) {
// catch the error
console.error(`
${e.message}
`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment