Algorithm
원형배열로 구현한 Queue
일등하이
2020. 10. 7. 17:37
반응형
using System;
using System.Collections.Generic;
namespace test_01
{
public class App
{
//생성자
public App()
{
// for (int i = 0; i < 11; i++)
// {
// Console.WriteLine(i % 10);
// }
Queue queue = new Queue();
queue.Enqueue(1);
queue.Enqueue(2);
var data = queue.Dequeue();
Console.WriteLine("Dequeue: " + data);
data = queue.Dequeue();
Console.WriteLine("Dequeue: " + data);
data = queue.Dequeue();
Console.WriteLine("Dequeue: " + data);
// queue.EnQueue(3);
// queue.EnQueue(4);
}
}
}
using System;
namespace test_01
{
public class Queue
{
public object[] arr;
public int front;
public int rear;
//생성자
public Queue(int size = 10)
{
this.arr = new object[size];
this.front = -1;
this.rear = -1;
}
public void Enqueue(object item)
{
//가득찼는지 확인
if ((rear + 1) % this.arr.Length == front)
{
throw new ApplicationException("Full.");
}
else
{
//비어 있는 경우
if (front == -1)
{
front++;
}
//데이터 추가
rear = (rear + 1) % this.arr.Length;
this.arr[rear] = item;
}
}
public object Dequeue()
{
//비어있는지 체크
if (this.front == -1 && this.rear == -1)
{
throw new ApplicationException("Empty");
}
else
{
//데이터 읽기
var data = this.arr[this.front];
//마지막 요소인경우
if (this.front == this.rear)
{
//초기화
this.front = -1;
this.rear = -1;
}
else
{
this.front = (this.front + 1) % this.arr.Length;
}
return data;
}
}
}
}
반응형