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

โปรแกรม C++ ใช้งาน Stack (พิลา)


ในโปรแกรมนี้เราจะดูวิธีการใช้งาน Stack ด้วย C++ Stack เป็นโครงสร้างข้อมูลนามธรรมที่มีชุดขององค์ประกอบ Stack ใช้กลไก LIFO (Last In First Out) คือองค์ประกอบที่ push เข้าไปทีหลังจะถูก pop ออกมาก่อน การดำเนินการหลักของ Stack มีดังนี้

  • Push - เพิ่มค่าข้อมูลไปที่ด้านบนของ stack

  • Pop - นำค่าข้อมูลที่อยู่ด้านบนของ stack ออก

  • Peek - คืนค่าข้อมูลที่อยู่ด้านบนของ stack

โปรแกรมที่ใช้งาน stack ด้วยอาร์เรย์ ดังนี้

Input: Push elements 11, 22, 33, 44, 55, 66
Output: Pop elements 66, 55, 44, 33, 22, 11

อัลกอริทึม

push(item)

Begin
    เพิ่มตัวชี้ top ขึ้น 1
    ใส่ item ลงในตำแหน่ง top
End

pop()

Begin
    item = องค์ประกอบด้านบนจาก stack
    ลดตัวชี้ top ลง 1
    return item
End

peek()

Begin
    item = องค์ประกอบด้านบนจาก stack
    return item
End

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

#include <iostream>
using namespace std;

int stack[100], n = 100, top = -1;

void push(int val) {
    if(top >= n-1)
        cout<<"Stack Overflow"<<endl;
    else {
        top++;
        stack[top] = val;
    }
}

void pop() {
    if(top <= -1)
        cout<<"Stack Underflow"<<endl;
    else {
        cout<<"The popped element is "<< stack[top] <<endl;
        top--;
    }
}

void display() {
    if(top>= 0) {
        cout<<"Stack elements are:";
        for(int i = top; i>= 0; i--)
            cout<<stack[i]<<" ";
        cout<<endl;
    } else
        cout<<"Stack is empty";
}

int main() {
    int ch, val;
    cout<<"1) Push in stack"<<endl;
    cout<<"2) Pop from stack"<<endl;
    cout<<"3) Display stack"<<endl;
    cout<<"4) Exit"<<endl;
    
    do {
        cout<<"Enter choice: "<<endl;
        cin>>ch;
        switch(ch) {
            case 1: {
                cout<<"Enter value to be pushed:"<<endl;
                cin>>val;
                push(val);
                break;
            }
            case 2: {
                pop();
                break;
            }
            case 3: {
                display();
                break;
            }
            case 4: {
                cout<<"Exit"<<endl;
                break;
            }
            default: {
                cout<<"Invalid Choice"<<endl;
            }
        }
    }while(ch != 4);
    return 0;
}

ผลลัพธ์

1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit