同理
顺序队列:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_05
{
interface IQueue<T>
{
int Count { get; }
int GetLength();
bool IsEmpty();
void Clear();
void Enqueue(T item);
T Dequeue();
T Peek();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_05
{
class SeQueue<T>:IQueue<T>
{
private T[] data;
private int count;
private int front;
private int rear;
public SeQueue(int size)
{
data = new T[size];
count = 0;
front = -1;
rear = -1;
}
public SeQueue():this(10) { }
public int Count
{
get { return count; }
}
public int GetLength()
{
return count;
}
public bool IsEmpty()
{
return count == 0;
}
public void Clear()
{
count = 0;
front = rear = -1;
}
public void Enqueue(T item)
{
if (count == data.Length)
{
Console.WriteLine("队列已满");
}
else
{
if (rear == data.Length - 1)
{
data[0] = item;
rear = 0;
count++;
}
else
{
data[rear + 1] = item;
rear++;
count++;
}
}
}
public T Dequeue()
{
if (count > 0)
{
T temp = data[front+1];
front++;
count--;
return temp;
}
else
{
Console.WriteLine("队列为空");
return default(T);
}
}
public T Peek()
{
T temp = data[front + 1];
return temp;
}
}
}
链队列
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_05
{
class Node<T>
{
private T data;
private Node<T> next;
public Node(T data)
{
this.data = data;
}
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_05
{
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;
}
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++;
}
}
public T Dequeue()
{
if (count == 0)
{
Console.WriteLine("队列为空,无法出队");
return default(T);
}
else if (count == 1)
{
T temp = front.Data;
front = rear = null;
count = 0;
return temp;
}
else
{
T temp = front.Data;
front = front.Next;
count--;
return temp;
}
}
public T Peek()
{
if (front != null)
{
return front.Data;
}
else
{
return default(T);
}
}
}
}