Unity/자료구조

[3.30] Queue 연습 1 (원형배열)

ljw4104 2021. 3. 30. 11:42
using System;

namespace Study01
{
    public class Queue
    {
        private string[] arr;
        private int front;
        private int rear;

        public Queue(int capacity = 4)
        {
            arr = new string[capacity];
            front = rear = -1;
        }

        public void Enqueue(string element)
        {
            if ((this.rear + 1) % this.arr.Length == this.front)
            {
                Console.WriteLine("Queue is fulled.");
                Console.WriteLine("배열 확장 후 진행합니다.");
                ResizeArray();
            }

            if (this.front == -1)
            {
                this.front++;
            }

            this.arr[++this.rear % this.arr.Length] = element;
        }

        public string Dequeue()
        {
            string result = string.Empty;
            if (front == -1 && rear == -1)
            {
                Console.WriteLine("Queue is empty.");
            }
            else
            {
                result = this.arr[this.front++ % this.arr.Length];
                if (this.front == this.rear)
                {
                    this.front = this.rear = -1;
                }
            }
            return result;
        }

        public void Print()
        {
            for (int i = this.front; i != (this.rear + 1) % this.arr.Length; i = (i + 1) % this.arr.Length)
            {
                Console.Write("{0} ", this.arr[i]);
            }
            Console.WriteLine();
        }

        private void ResizeArray()
        {
            var temp = new string[arr.Length * 2];
            for (int i = 0; i < arr.Length; i++)
            {
                temp[i] = arr[i];
            }
            arr = temp;
        }
    }
}
using System;

namespace Study01
{
    public class App
    {
        public App()
        {
            Queue queue = new Queue(4);
            queue.Enqueue("홍길동");
            queue.Enqueue("임꺽정");
            queue.Enqueue("장길산");
            queue.Enqueue("고길동");
            queue.Enqueue("asdf");
            queue.Enqueue("qwerty");

            queue.Print();

            queue.Dequeue();
            queue.Dequeue();
            queue.Dequeue();
            queue.Enqueue("둘리");

            queue.Print();
        }
    }
}