STACK
Dalam C++, stack adalah struktur data yang mengikuti prinsip LIFO (Last In, First Out). Artinya, elemen terakhir yang dimasukkan ke dalam stack adalah elemen pertama yang dikeluarkan. Stack digunakan untuk menyimpan dan mengelola data dalam urutan tertentu, di mana operasi utama yang dapat dilakukan adalah:
Push: Menambahkan elemen ke atas stack.
Pop: Menghapus elemen teratas dari stack.
Top (Peek): Mengakses elemen teratas tanpa menghapusnya.
IsEmpty: Memeriksa apakah stack kosong.
Size: Mengembalikan jumlah elemen dalam stack.
Struktur data stack sering digunakan dalam berbagai aplikasi pemrograman seperti pemrosesan ekspresi aritmatika, penelusuran graf, dan implementasi fungsi rekursif. Di C++, stack dapat diimplementasikan secara manual menggunakan array atau linked list, atau dengan menggunakan pustaka standar <stack>.
Salah satu contohnya sebagai berikut :
// judul : stack tanpa library stack
// manual
#include <iostream>
using namespace std;
// kamus
struct Stack {
int top;
int max_size;
int* stack_array;
};
// Function to initialize the stack
void initializeStack(Stack& stack, int size) {
stack.max_size = size;
stack.stack_array = new int[size];
stack.top = -1;
}
// Function to clean up the stack
void destroyStack(Stack& stack) {
delete[] stack.stack_array;
}
// Function to push an element onto the stack
void push(Stack& stack, int value) {
if (stack.top >= stack.max_size — 1) {
cout << “Stack overflow” << endl;
return;
}
stack.stack_array[++stack.top] = value;
}
// Function to pop an element from the stack
int pop(Stack& stack) {
if (stack.top < 0) {
cout << “Stack underflow” << endl;
return -1;
}
return stack.stack_array[stack.top — ];
}
// Function to peek at the top element of the stack
int peek(const Stack& stack) {
if (stack.top < 0) {
cout << “Stack is empty” << endl;
return -1;
}
return stack.stack_array[stack.top];
}
// Function to check if the stack is empty
bool isEmpty(const Stack& stack) {
return stack.top < 0;
}
// Function to get the current size of the stack
int size(const Stack& stack) {
return stack.top + 1;
}
int main() {
Stack stack;
initializeStack(stack, 5); // Create a stack of size 5
push(stack, 10);
push(stack, 20);
push(stack, 30);
push(stack, 40);
push(stack, 50);
cout << “Top element is: “ << peek(stack) << endl; // Should print 50
cout << “Stack size is: “ << size(stack) << endl; // Should print 5
cout << “Popped element: “ << pop(stack) << endl; // Should print 50
cout << “Popped element: “ << pop(stack) << endl; // Should print 40
cout << “Top element is: “ << peek(stack) << endl; // Should print 30
push(stack, 60);
cout << “Top element is: “ << peek(stack) << endl; // Should print 60
while (!isEmpty(stack))
{
cout << “Popped element: “ << pop(stack) << endl;
}
cout << “Stack size is: “ << size(stack) << endl; // Should print 0
destroyStack(stack); // Clean up the stack
return 0;
}
Dan ini hasilnya :

Komentar
Posting Komentar