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

โปรแกรม C++ สำหรับการใช้งาน Stack ใน STL

Stack (สแต็ก) เป็นโครงสร้างข้อมูลแบบเส้นตรงที่ปฏิบัติตามลำดับเฉพาะในการดำเนินการ ลำดับอาจเป็น FILO (First In Last Out) หรือ LIFO (Last In First Out) ซึ่งทั้งคู่นี้หมายถึงสิ่งเดียวกันคือ "ตัวที่เข้าสุดท้ายจะออกก่อน"

อัลกอริธึมและฟังก์ชันหลัก

  • s.size() – คืนขนาดของสแต็ก
  • s.push() – ใช้แทรกองค์ประกอบเข้า สแต็ก
  • s.pop() – นำค่าออกจาก สแต็ก (ค่าที่อยู่บนสุด)
  • s.top() – คืนอ้างอิงไปยังองค์ประกอบบนสุดของ สแต็ก
  • s.empty() – ตรวจสอบว่า สแต็กว่างหรือไม่ (สำคัญสำหรับความปลอดภัย)

โค้ดตัวอย่าง (โปรแกรมโต้ตอบแบบเมนู)

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

int main() {
    stack<int> s;
    int c, i;

    while (true) {
        cout << "1.Size of the Stack" << endl;
        cout << "2.Insert Element into the Stack" << endl;
        cout << "3.Delete Element from the Stack" << endl;
        cout << "4.Top Element of the Stack" << endl;
        cout << "5.Exit" << endl;
        cout << "Enter your Choice: ";
        cin >> c;

        switch(c) {
            case 1:
                cout << "Size of the stack: " << s.size() << endl;
                break;
            case 2:
                cout << "Enter value to be inserted: ";
                cin >> i;
                s.push(i);
                break;
            case 3:
                if (!s.empty()) {
                    i = s.top();
                    s.pop();
                    cout << i << " Deleted" << endl;
                } else {
                    cout << "Stack is Empty" << endl;
                }
                break;
            case 4:
                if (!s.empty())
                    cout << "Top Element of the Stack: " << s.top() << endl;
                else
                    cout << "Stack is Empty" << endl;
                break;
            case 5:
                exit(0);
            default:
                cout << "Wrong Choice" << endl;
        }
    }
    return 0;
}

ตัวอย่างผลลัพธ์

1.Size of the Stack
2.Insert Element into the Stack
3.Delete Element from the Stack
4.Top Element of the Stack
5.Exit
Enter your Choice: 1
Size of the stack: 0
Enter your Choice: 2
Enter value to be inserted: 1
Enter your Choice: 2
Enter value to be inserted: 7
Enter your Choice: 2
Enter value to be inserted: 6
Enter your Choice: 2
Enter value to be inserted: 10
Enter your Choice: 2
Enter value to be inserted: 4
Enter your Choice: 1
Size of the stack: 5
Enter your Choice: 3
4 Deleted
Enter your Choice: 4
Top Element of the Stack: 10
Enter your Choice: 5
Exit code: 0

ข้อสังเกต: โค้ดต้นฉบับเรียก s.top() ก่อนตรวจสอบ empty() ซึ่งอันตราย หากสแต็กว่าง โค้ดที่ปรับปรุงแล้วตรวจสอบ empty() ก่อนทุกครั้ง