هياكل البيانات
تنفيذ الـStack
يعرف هذا البرنامج stack class بسيطة مع عمليات أساسية مثل push, pop, getTop, وprint. إليك تفاصيل البرنامج:
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int top; // Index of the top element in the stack
int item[MAX_SIZE]; // Array to store stack elements
public:
// Constructor: Initializes top to -1 (empty stack)
Stack() : top(-1) {}
// Function to push an element onto the stack
void push(int Element) {
if (top >= MAX_SIZE - 1) {
cout << "Stack is full on push" << endl;
} else {
top++;
item[top] = Element;
}
}
// Function to check if the stack is empty
bool isEmpty() {
return top < 0;
}
// Function to pop an element from the stack
void pop() {
if (isEmpty()) {
cout << "Stack is empty on pop" << endl;
} else {
top--;
}
}
// Function to get the top element of the stack
void getTop(int& stackTop) {
if (isEmpty()) {
cout << "Stack is empty on getTop" << endl;
} else {
stackTop = item[top];
cout << stackTop << endl;
}
}
// Function to print the elements of the stack
void print() {
cout << "[";
for (int i = top; i >= 0; i--) {
cout << item[i] << " ";
}
cout << "]" << endl;
}
};
int main() {
Stack s;
// Push elements onto the stack
s.push(5);
s.push(10);
s.push(15);
s.push(20);
// Print the stack
s.print();
// Get and print the top element of the stack
int y = 0;
s.getTop(y);
// Pop an element from the stack
s.pop();
// Push another element onto the stack
s.push(7);
// Print the stack again
s.print();
return 0;
}
شرح:
- تنفذ Stack class باستخدام عنصر مصفوفة مسماة item . يحتوي على دوال الأعضاء push, pop, getTop, isEmpty, وprint.
- في دالة push ، إذا لم تكن الـstack ممتلئة، فإنها تزيد الـ top index وتضيف العنصر إلى مصفوفة العناصر في الـ top index.
- تتحقق الدالة isEmpty مما إذا كان الـ stack فارغًا عن طريق مقارنة الـ top index بـ -1.
- تقوم الدالة pop بتقليل الـ top index إذا لم يكن الـ stack فارغًا.
- تقوم الدالة getTop باسترداد الـ top element للستاك وتخزينه في stackTop.
- تقوم دالة الطباعة بطباعة عناصر الستاك من الأعلى إلى الأسفل.
- في الدالة الرئيسية، يتم إنشاء كائن الستاك وتنفيذ عمليات مختلفة مثل push, pop, getTop, وprint.