Stack cài bằng mảng
user_1746670
c_cpp
a year ago
1.6 kB
9
Indexable
// Cài đặt stack sử dụng mảng
#include <bits/stdc++.h>
using namespace std;
#define MAX 1005
struct Stack {
int n;
int a[MAX];
Stack() : n(0) {}
};
// full
bool Full(Stack st) {
return st.n == (MAX - 1);
}
// empty
bool Empty(Stack st) {
return st.n == 0;
}
// push
void pushStack(Stack &st, int x) {
if (Full(st)) {
cout << "Khong push duoc" << endl;
return;
} else {
st.n++;
st.a[st.n - 1] = x;
}
}
// pop
void popStack(Stack &st) {
if (Empty(st)) {
cout << "Khong pop duoc" << endl;
return;
} else {
st.n--;
st.a[st.n + 1] = 0;
}
}
// top
bool topStack(Stack st, int& x) {
if (Empty(st)) {
cout << "Stack rong" << endl;
return false;
} else {
x = st.a[st.n - 1];
return true;
}
}
// print
void printStack(Stack st) {
while (!Empty(st)) {
int x;
if (topStack(st, x)) {
cout << x << " ";
}
popStack(st);
}
cout << endl;
}
int main() {
Stack st;
pushStack(st, 4);
pushStack(st, 2);
pushStack(st, 3);
pushStack(st, 7);
pushStack(st, 5);
pushStack(st, 9);
printStack(st);
popStack(st);
popStack(st);
popStack(st);
popStack(st);
printStack(st);
popStack(st);
popStack(st);
int x;
if (topStack(st, x)) {
cout << "top = " << x << endl;
}
return 0;
}Editor is loading...
Leave a Comment