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

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


Abstract Data Type (ADT)

ADT เป็นชนิดข้อมูลพิเศษ ที่พฤติกรรมถูกกำหนดโดยชุดค่าและชุดการดำเนินการ "Abstract" เพราะเราใช้งานและดำเนินการได้ แต่วิธีการทำงานภายในถูกซ่อนไว้ ADT สร้างจาก Primitive Data Types แต่อัลกอริทึมภายในถูกปิดบัง

การดำเนินการของ Stack ADT

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

ตัวอย่างโค้ด C++

#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;
    }
    // Insert elements
    stk.push(10);
    stk.push(20);
    stk.push(30);
    stk.push(40);
    stk.push(50);
    cout << "Size of the stack: " << stk.size() << endl;
    // Pop and display
    while (!stk.empty()) {
        int item = stk.top(); // same as peek
        stk.pop();
        cout << item << " ";
    }
}

Output

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