Membuat Codingan C++ STACK

#include <iostream>
#define max 10

using namespace std;

class Stack{
public:
void init();
bool kosong();
bool penuh();
void push();
void pop();
void tampil();
int top, data[max];
}stack;

void Stack::init(){
stack.top = -1;
}

bool Stack::kosong() {
return stack.top == -1;
}

bool Stack::penuh(){
return stack.top == max-1;
}

void Stack::push(){
if(penuh()){
cout << "data penuh";
}else{
stack.top++;
cout << " Masukan data : ";
cin >> stack.data[stack.top];
cout << " Data telah ditambah : " << stack.data[stack.top] <<
" Masuk ke Stack";
}
}

void Stack::pop(){
if(kosong()){
cout << " Kosong !";
}else{
cout << " Data  : "<< stack.data[stack.top] <<
" sudah terambil";
stack.top--;
}
}

void Stack::tampil(){
if(kosong()){
cout << " data kosong";
}else{
int a = 0;
cout << " Data : \n";
for(int i=stack.top; i>=0; i--){
cout << " ("<<i<<") -> " << stack.data[i] << "\t";
a++;
if(a%5==0)
cout << endl;
}
}
}

int main(){
float pilih;

cout << "\n ------------ Pilih -------------";

stack.init();
do{
cout << "\n\n 1 PUSH\n 2 POP\n 3 Tampil\n 4 EXIT";
cout << "\n Masukan pilihan anda : ";
cin >> pilih;
switch((int)pilih){
case 1:
stack.push();
break;
case 2:
stack.pop();
break;
case 3:
stack.tampil();
break;
case 4:
cout << " EXIT!";
break;
default :
cout << " Syntax Eror!";
}
}while(pilih!=4);

return 0;
}

Posting Komentar

Lebih baru Lebih lama