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++;
}
这样不会两个重复的元素吗?