Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การ Implement Stack (สแต็ก) ใน JavaScript

Stack เป็นโครงสร้างข้อมูลแบบ LIFO (Last In, First Out) - ตัวสุดท้ายเข้าตัวแรกออก ใช้ใน Undo/Redo, Expression Evaluation, Backtracking, Function Call Stack

ตัวอย่างโค้ด (Class-based)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Stack Implementation</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: blueviolet; }
    button { padding: 6px; margin: 4px; }
  </style>
</head>
<body>
  <h1>Implementation of Stack ใน JavaScript</h1>
  <div class="result"></div>
  <br />
  <input type="text" class="stackPush" placeholder="Value" />
  <button class="pushBtn">Push</button>
  <button class="popBtn">Pop</button>
  <button class="Btn">Display</button>
  <h3>คลิกปุ่มด้านบนเพื่อทำ Stack Operations</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    const pushBtnEle = document.querySelector(".pushBtn");
    const popBtnEle = document.querySelector(".popBtn");
    
    class Stack {
      constructor() {
        this.items = [];
      }
      
      push(element) {
        this.items.push(element);
      }
      
      pop() {
        if (this.isEmpty()) {
          return "Underflow: Stack is empty";
        }
        return this.items.pop();
      }
      
      peek() {
        return this.isEmpty() ? "Empty" : this.items[this.items.length - 1];
      }
      
      isEmpty() {
        return this.items.length === 0;
      }
      
      size() {
        return this.items.length;
      }
      
      display() {
        if (this.isEmpty()) {
          resEle.innerHTML = "Stack is empty";
          return;
        }
        // แสดงจาก Top ลงมา (LIFO Order)
        for (let i = this.items.length - 1; i >= 0; i--) {
          resEle.innerHTML += `${this.items[i]} `;
        }
      }
    }
    
    const stack1 = new Stack();
    
    BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "";
      stack1.display();
    });
    
    pushBtnEle.addEventListener("click", () => {
      const val = document.querySelector(".stackPush").value;
      if (val) {
        stack1.push(val);
        resEle.innerHTML = `${val} pushed to stack`;
        document.querySelector(".stackPush").value = "";
      }
    });
    
    popBtnEle.addEventListener("click", () => {
      const popped = stack1.pop();
      resEle.innerHTML = `${popped} popped from stack`;
    });
  </script>
</body>
</html>

Stack Operations

OperationDescriptionTime
push(item)เพิ่ม Item บนสุดO(1)
pop()ลบและคืน Item บนสุดO(1)
peek()/top()ดู Item บนสุด (ไม่ลบ)O(1)
isEmpty()เช็คว่าว่างไหมO(1)
size()จำนวน ItemsO(1)

تطبيقاتจริง (Real Applications)

  • Undo/Redo: เก็บ State History
  • Expression Evaluation: Infix to Postfix, คำนวณ Postfix
  • Browser History: Back/Forward Button
  • Function Call Stack: JavaScript Engine ใช้เอง
  • Balanced Parentheses: ตรวจสอบ (), {}, []
  • DFS (Depth-First Search): Graph Traversal

ผลลัพธ์

UI แสดงค่าที่ Push/Pop และ Display Stack Contents (Top to Bottom)