22
Eki
2025

Veri yapıları ve algoritmalar II dersi – Yığın

 

#include<iostream>
#include <locale.h>
using namespace std;

// Yigin veri yapisi
struct stack{
  int boyut;
  int *elemanlar;
  int ust;
};

// Yeni bir yigin olusturma fonksiyonu
stack* createStack(int boyut)
{
  stack *yigin = new stack;
  yigin->boyut = boyut;
  yigin->ust = -1;
  yigin->elemanlar = new int[boyut];
  return yigin;
}

// Yigin bos mu?
bool isEmpty(stack &yigin)
{
  if (yigin.ust == -1)
    return true;
  else
    return false;
}

//Yigin dolu mu?
bool isFull(stack &yigin)
{
  if (yigin.ust == yigin.boyut-1)
    return true;
  else
    return false;
}

// Yigina eleman ekle
bool push(stack &yigin, int veri)
{
  if (isFull(yigin) == false)
  {
    yigin.elemanlar[++yigin.ust] = veri;
    cout<<yigin.elemanlar[yigin.ust]<<" eklendi. Yeni üst:"<<yigin.ust<<endl;
    return true;
  }
  cout<<"Yigin dolu";
    return false;
}

// Yigindan eleman çikarma
bool pop(stack &yigin) 
{
  if (isEmpty(yigin) == false)
  {
    cout<<yigin.elemanlar[yigin.ust]<<" çikarildi"<<endl;	    
    yigin.elemanlar[yigin.ust--] = NULL;
    return true;
  }
  cout<<"Yigin zaten bos"<<endl;
  return false;	
}

// En üst elemani yazdirma
void peek(stack &yigin)
{
  cout<<"En üst eleman: "<<yigin.elemanlar[yigin.ust]<<", en üst indeks: "<<yigin.ust<<endl;
}

// Tüm yigini ekrana yazdir.
void display(stack  &yigin)
{
  if (isEmpty(yigin) == false)
  {
    for (int i = 0; i<=yigin.ust; i++)
      cout<<yigin.elemanlar[i]<<endl;
  }
  else cout<<"Yigin bos";	
}

main()
{
  setlocale(LC_ALL, "Turkish");
  
  // Baslangiç adresi yigin olan 10 elemanli bir integer yigini olusturulsun
  stack *yigin = createStack(10);
  
  // Yigin dolu mu?
  //cout<<isEmpty(*yigin);
  
  // Yigin bos mu?
  //cout<<isFull(*yigin);
  
  // Ekleme
  push(*yigin, 23);
  push(*yigin, 21);
  push(*yigin, 13);
  push(*yigin, 3);
  push(*yigin, 11);
  push(*yigin, 15);
  
  display(*yigin);
  
  pop(*yigin);
  pop(*yigin);
  peek(*yigin);
  pop(*yigin);
  pop(*yigin);
  pop(*yigin);
  pop(*yigin);
  pop(*yigin);
  pop(*yigin);
}

 

 

error: içerik koruması