Stack: Pop Operation (টপ এলিমেন্ট রিমুভ করা)
Pop মানে স্ট্যাকের টপ (সাম্প্রতিক যোগ করা) এলিমেন্টটি সরিয়ে ফেলা এবং তার মান রিটার্ন করা। অ্যারের শেষে (index = length-1) থেকে এলিমেন্ট রিমুভ হয়।
Pop মেথড ইমপ্লিমেন্টেশন
class Stack {
constructor(maxSize = 10) {
this.maxSize = maxSize;
this.container = [];
}
isEmpty() {
return this.container.length === 0;
}
// Pop Implementation
pop() {
// খালি স্ট্যাক চেক
if (this.isEmpty()) {
console.log("Stack Underflow! স্ট্যাক খালি, পপ সম্ভব নয়।");
return undefined;
}
// pop() দিয়ে শেষ এলিমেন্ট সরিয়ে আনে
return this.container.pop();
}
// Helper methods
push(element) { /* ... */ }
display() { console.log(this.container); }
}
টেস্টিং উদাহরণ
const s = new Stack(3);
s.display(); // []
// খালি স্ট্যাকে পপ
s.pop(); // "Stack Underflow!" + undefined
s.push(20);
s.push(30);
s.display(); // [ 20, 30 ]
s.pop(); // 30 রিটার্ন, স্ট্যাক: [ 20 ]
s.display(); // [ 20 ]
আউটপুট ব্যাখ্যা
[] Stack Underflow! স্ট্যাক খালি, পপ সম্ভব নয়। [ 20, 30 ] [ 20 ]
৩০ শেষে পুশ করা হয়েছিল, তাই এটি প্রথমে পপ হয় (LIFO)। ২০ বাকি থাকে।
Pop vs Push vs Peek
| মেথড | অপারেশন | রিটার্ন | স্ট্যাক পরিবর্তন |
|---|---|---|---|
| push(x) | টপে x যোগ | Boolean / new length | সাইজ +১ |
| pop() | টপ এলিমেন্ট সরিয়ে ফেলা | সরানো এলিমেন্ট | সাইজ -১ |
| peek() | টপ এলিমেন্ট দেখা | টপ এলিমেন্ট | কোনো পরিবর্তন নেই |
Underflow Handling Strategies
// ১. Throw Error (Production Recommended)
pop() {
if (this.isEmpty()) throw new Error("Stack Underflow");
return this.container.pop();
}
// ২. Return undefined (Simple)
pop() {
if (this.isEmpty()) return undefined;
return this.container.pop();
}
// ৩. Return { value, success } Object
pop() {
if (this.isEmpty()) return { value: undefined, success: false };
return { value: this.container.pop(), success: true };
}
বাস্তব ব্যবহার: ব্র্যাকেট ম্যাচিং (Parentheses Validation)
function isValidParentheses(str) {
const stack = new Stack(str.length);
const pairs = { ')': '(', '}': '{', ']': '[' };
for (const char of str) {
if ('({['.includes(char)) {
stack.push(char);
} else if (')}]'.includes(char)) {
if (stack.isEmpty() || stack.pop() !== pairs[char]) {
return false;
}
}
}
return stack.isEmpty();
}
console.log(isValidParentheses("({[]})")); // true
console.log(isValidParentheses("({[})")); // false