C#环形队列

using System;
namespace A
{
    class MyQueue<T>
    {
        private int head;
        private int tail;
        private int curLength;
        private int capacity;
        private T[] queue;

        public MyQueue(int cap)
        {
            head = 0;
            tail = 0;
            curLength = 0;
            capacity = cap;
            queue = new T[capacity];
        }

        public bool isEmpty() { return curLength == 0; }
        public bool isFull() { return curLength == capacity; }
        public bool EnQueue(T node)
        {
            if (!isFull())
            {
                queue[tail] = node;
                tail = (++tail) % capacity;
                curLength++;
                return true;
            }
            return false;
        }
        public T DeQueue()
        {
            T result = default(T);
            if (!isEmpty())
            {
                result = queue[head];
                head = (++head) % capacity;
                curLength--;
                return result;
            }
            return result;
        }
        public int GetCapacity()
        {
            return capacity;
        }
        public void Transver()
        {
            for (int i = head; i < head+curLength; i++)
            {
                Console.WriteLine(queue[i%capacity]);
                Console.WriteLine($"前面还有{i-head}个");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyQueue<int> queue = new MyQueue<int>(6);
            Console.WriteLine(queue.DeQueue()); 
            for (int i = 0; i < queue.GetCapacity(); i++)
            {
                queue.EnQueue(i * 10);
            }
            queue.Transver();

            queue.DeQueue();
            Console.WriteLine();
            queue.Transver();

            queue.DeQueue();
            queue.EnQueue(30);
            Console.WriteLine(queue.EnQueue(40));
            Console.WriteLine(queue.EnQueue(40));
            Console.WriteLine();
            queue.Transver();
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kerven_HKW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值