1. 程式人生 > 實用技巧 >資料結構和演算法-陣列佇列

資料結構和演算法-陣列佇列

佇列:

佇列是一個有序列表,遵循先入先出原則,可以用陣列或連結串列實現

使用場景

用於排隊,按順序執行

客戶端:

public static void Main(string[] args)
        {
            ArrayQueue<int> queue = new ArrayQueue<int>(1000);
            queue.Push(1);
            queue.Push(2);
            queue.Push(3);
            queue.Push(4);
            queue.Push(5);

            Console.WriteLine(queue.Pop());
            Console.WriteLine(queue.Pop());
            queue.Push(6);
            queue.Push(7);
            queue.Print();
            Console.ReadKey();
        }

陣列佇列

public class ArrayQueue<T>
    {
        private int _front = -1;//隊首
        private int _rear = -1;//隊尾
        private int _maxSize = 0;
        private T[] _arr = null;
        public ArrayQueue(int maxSize)
        {
            _maxSize = maxSize;
            _arr = new T[maxSize];
        }
        public bool IsFull()
        {
            return _rear >= _maxSize - 1;
        }
        public bool IsEmpty()
        {
            return _front >= _rear;
        }
        public void Push(T n)
        {
            if (this.IsFull())
            {
                throw new Exception("佇列已滿");
            }
            _arr[++_rear] = n;
        }
        public T Pop()
        {
            if (this.IsEmpty())
            {
                throw new Exception("佇列已空");
            }
            return _arr[++_front];
        }
        public void Print()
        {
            if (this.IsEmpty())
            {
                Console.WriteLine("佇列已空");
                return;
            }
            for (int i = _front+1; i <= _rear; i++)
            {
                Console.WriteLine($"{i}:{_arr[i]}");
            }
        }


    }