Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(196评价)
价格: 4069.00元
数据结构中的队列的问题(17课时)
sdewqazxcds发起了问答2017-09-18
1
回复
1235
浏览
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _003_队列
{
    /// <summary>
    /// 链队列的实现
    /// </summary>
    class LinkQueue<T> : IQueue<T>
    {
        private Node<T> front;//头节点
        private Node<T> rear;//尾节点
        private int count;//表示元素的个数

        public LinkQueue()
        {
            front = null;
            rear = null;
            count = 0;
        }

        public int Count
        {
            get { return count; }
        }


        public int GetLength()
        {
            return Count;
        }

        public bool IsEmpty()
        {
            return count == 0;
        }

        public void Clear()
        {
            front = null;
            rear = null;
            count = 0;
        }

        /// <summary>
        /// 入队
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue(T item)
        {
            Node<T> newNode=new Node<T>(item);
            if (count == 0)//头节点
            {
                front = newNode;
                rear = newNode;
                count = 1;
            }
            else//当队列中有数据时
            {
                rear.Next = newNode;//新的节点是尾节点(入队都是从尾节点入)
                rear = newNode;
                count++;
            }
        }

        /// <summary>
        /// 出队
        /// </summary>
        /// <returns></returns>
        public T Dequeue()
        {
            if (count == 0)
            {
                Console.WriteLine("队列为空,无法出队");
                return default(T);
            }else if (count == 1) //队列为1个数据
            {
                T temp = front.Data; //输出头节点
                front = rear = null; //清空头尾
                count = 0;
                return temp;
            }
            else
            {
                T temp = front.Data;//要入队的数据
                front = front.Next;//先把队头存放到后一位
                count--;//数量-1
                return temp;
            }
        }

        /// <summary>
        /// 取得队列头部数据
        /// </summary>
        /// <returns></returns>
        public T Peek()
        {
            if (front != null)
            {
                return front.Data;
            }
            else
            {
                return default(T);
            }
        }
    }
}

在入队Enqueue函数不太懂,

            else//当队列中有数据时
            {
                rear.Next = newNode;//新的节点是尾节点(入队都是从尾节点入)
                rear = newNode;
                count++;
            }

这样不会两个重复的元素吗?

 

所有回复
  • siki 2017-09-18

    为什么会有重复元素呢,这里不是把最后结点的引用指向新添加的数据结点,这个新添加的数据就设置为了尾结点

    这里哪里会重复呢

    还有-5条回复,点击查看
    你还没有登录,请先登录注册
发表回复
你还没有登录,请先 登录或 注册!