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

Stack Primitive Operations ในโครงสร้างข้อมูล


Stack: LIFO (Last In First Out)

ใช้ใน Expression Evaluation, Function Call/Recursion ADT ซ่อนรายละเอียดภายใน

Stack ADT Operations

  • isFull() – ตรวจสอบ Stack เต็ม
  • isEmpty() – ตรวจสอบ Stack ว่าง
  • push(x) – ใส่ x เข้า Stack
  • pop() – ลบจาก Top
  • peek() – ดูค่า Top
  • size() – จำนวนองค์ประกอบ

ตัวอย่าง C++ (STL Stack)

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> stk;
    if (stk.empty()) cout << "Stack is empty" << endl;
    else cout << "Stack is not empty" << endl;
    stk.push(10); stk.push(20); stk.push(30); stk.push(40); stk.push(50);
    cout << "Size of the stack: " << stk.size() << endl;
    while (!stk.empty()) {
        int item = stk.top();  // peek
        stk.pop();
        cout << item << " ";
    }
}

Output

Stack is empty
Size of the stack: 5
50 40 30 20 10