Yığınlar

Veri Yapıları dersinde işlenen Stack konusunu bu gönderi altında inceleyebilirsiniz.

Örnek-1:


using System;
namespace stack
{
class Program
{
static int sp = -1;
static int[] stack = new int[100];
static public void push(int data)
{
sp++;
stack[sp] = data;
}
static public int pop()
{
int data = stack[sp];
sp--;
return data;
}
static void Main(string[] args)
{
push(10);
push(20);
push(30);
push(40);
for (int i = 0; i < 4; i++)
{
Console.WriteLine(pop());
}
}
}
}

Örnek-2:


using System;

namespace stack_2
{
class Program
{
static int sp = -1;
static int max = 100;
static int[] stack = new int[max];
static public bool push(int data)
{
if (sp >= max)
{
Console.WriteLine("Stack Overflow");
return false;
}
else
{
sp++;
stack[sp] = data;
return true;
}
}
static public int pop()
{
if (sp < 0)
{
Console.WriteLine("Stack Underflow");
return 0;
}
else
{
int data = stack[sp];
sp--;
return data;
}
}
static public void printStack()
{
if (sp < 0)
{
Console.WriteLine("Stack Underflow");
return;
}
else
{
Console.WriteLine("Yığın İçeriği");
for (int i = sp; i >= 0; i--)
{
Console.WriteLine(stack[i]);
}
}
}
static public void Peek()
{
if (sp < 0)
{
Console.WriteLine("Stack Underflow");
return;
}
else
{
Console.WriteLine("Yığının en üstündeki eleman: {0}", stack[sp]);
}
}
static void Main(string[] args)
{
// Şu an sp=-1
push(10); // sp'yi 1 arttır. 10'u ekle sp = 0 stack[0] = 10;
push(20); // sp'yi 1 arttır 20'yi ekle sp = 1 stack[1] = 20;
push(30); // sp'yi 1 arttır 30'u ekle sp = 2 stack[2] = 30;
push(40); // sp'yi 1 arttır 40'ı ekle sp = 3 stack[3] = 40;
printStack();
Console.WriteLine("Stack'tan silindi: {0}", pop()); // 40'ı döndür sp'yi 1 azalt. sp = 2
Console.WriteLine("Stack'tan silindi: {0}", pop()); // 30'u döndür sp'yi 1 azalt. sp = 1
printStack();
Peek();
}
}
}