Breaking News
Loading...
Kamis, 28 April 2016

Stack with struct

using namespace std;

struct tumpukan{
 int stk;
};

tumpukan stack[11];

void menu ()
{
 cout<<"1.Push\n2. Pop\n3. Clear\n4. Print\n5. Exit\nPilihan Anda : "; //untuk menampilkan menu
}

int push (int j) //input data on the stack
{
 if (j<10)
 {
  if(j==-1)
  {
   j=0;//indikator index
   }
  cout<<"Masukkan Data (int) = ";
  cin>>stack[j].stk;//data stack yang diinput dan j sebagai nilai indexing arraynya
  //cout<<"Sebelum ditambah j++ : "<<j<<endl;
  cout<<"Data berhasil dipush\n";
  j++;//indexing arraynya bertambah 1
  //cout<<"Setelah ditambah j++ : "<<j<<endl;
  }
 else
 {
  cout<<"Stack penuh, harap lakukan pop data dahulu\n";
  }
 return j;
}

int pop (int j)
{
 if(j>=0)
 {
  cout<<"Nilai j : "<<j<<endl;
  j--;
  cout<<"Nilai j : "<<j<<endl;
  cout<<"Data "<<stack[j].stk<<" Dipop\n";
  }
 else
 {
  cout<<"Stack kosong,harap lakukan push data dahulu\n";
  }
 return j;
}

void print (int j)
{
 if(j>=0)
 {
  for(int i=j-1;i>=0;i--)
  {
   cout<<"["<<stack[i].stk<<"]\n";
   }
  //cout<<stack[1];
  }
 else
 {
  cout<<"Stack kosong,harap lakukan push terlebih dahulu\n";
  }
}

main ()
{
 int i=-1,pilih;

 start:
  system ("cls");
  menu ();
  cin>>pilih;
  if(pilih==1)
  {
   i=push(i);
   cout<<"Jumlah isi stack : "<<i<<endl;
   getch ();
   goto start;
   }
  else if (pilih==2)
  {
   i=pop(i);
   cout<<"Nilai i : "<<i<<endl;
   getch ();
   goto start;
   }
  else if (pilih==3)
  {
   for(int x=0;x<i;x++)
   {
    stack[x].stk=NULL;//NULL = kosong
    }
   i=-1;//mengubah index menjadi -1 berarti kosong/ngga ada array -1
   cout<<"Semua data terhapus\n";
   cout<<stack[1].stk;
   getch();
   goto start;
   }
  else if (pilih==4)
  {
   print(i);
   getch();
   goto start;
   }
  else if (pilih==5)
  {
   cout<<"\n\nTerima Kasih\n";
   }
  else
  {
   cout<<"Input salah\n";
   getch();
   goto start;
   }
  return 0;
}

0 komentar:

Posting Komentar

Copyright © 2012 IamChands All Right Reserved
Designed by CBTblogger