C#数组和链表实现队列
标签:line csharp efault returns write har sharp city default
//基于数组的队列实现
public class MyArrayQueue
{
private T[] items;
private int size;
private int head;
private int tail;
public MyArrayQueue(int capacity)
{
this.items = new T[capacity];
this.size = 0;
this.head = this.tail = 0;
}
///
/// 入队
///
/// 入队元素
public void EnQueue(T item)
{
if (Size == items.Length)
// 扩大数组容量
ResizeCapacity(items.Length * 2);
items[tail] = item;
tail++;
size++;
}
/// v
/// 出队
///
/// 出队元素
public T DeQueue()
{
if (size == 0) return default(T);
T item = items[head];
items[head] = default(T);
head++;
if (head > 0 && Size == items.Length / 4)
ResizeCapacity(items.Length / 2);
size--;
return item;
}
///
/// 重置数组大小
///
/// 新的容量
public void ResizeCapacity(int newCapacity)
{
T[] newItems = new T[newCapacity];
int index = 0;
if (newCapacity > items.Length)
{
for (int i = 0; i
/// 栈是否为空
///
/// true/false
public bool IsEmpty()
{
return this.size == 0;
}
///
/// 栈中节点个数
///
public int Size
{
get
{
return this.size;
}
}
}
public class Node
{
public T Item { get; set; }
public Node Next { get; set; }
public Node(T item)
{
this.Item = item;
}
public Node()
{ }
}
///
/// 基于链表的队列实现
///
/// 类型
public class MyLinkQueue
{
private Node head;
private Node tail;
private int size;
public MyLinkQueue()
{
this.head = null;
this.tail = null;
this.size = 0;
}
///
/// 入队操作
///
/// 节点元素
public void EnQueue(T item)
{
Node oldLastNode = tail;
tail = new Node();
tail.Item = item;
if (IsEmpty())
{
head = tail;
}
else
{
oldLastNode.Next = tail;
}
size++;
}
///
/// 出队操作
///
/// 出队元素
public T DeQueue()
{
T result = head.Item;
head = head.Next;
size--;
if (IsEmpty())
{
tail = null;
}
return result;
}
///
/// 是否为空队列
///
/// true/false
public bool IsEmpty()
{
return this.size == 0;
}
///
/// 队列中节点个数
///
public int Size
{
get
{
return this.size;
}
}
}
class Program
{
static void Main(string[] args)
{
// 01.基于链表的队列
QueueWithLinkListTest();
// 02.基于数组的队列
//QueueWithArrayTest();
}
#region Method01.基于链表的队列的测试
///
/// 基于链表的队列的测试
///
static void QueueWithLinkListTest()
{
MyLinkQueue queue = new MyLinkQueue();
Console.WriteLine("Is Empty:{0}", queue.IsEmpty());
Random rand = new Random();
// 顺序插入5个元素
for (int i = 0; i
/// 基于数组的队列的测试
///
static void QueueWithArrayTest()
{
MyArrayQueue queue = new MyArrayQueue(5);
Console.WriteLine("Is Empty:{0}", queue.IsEmpty());
Console.WriteLine("Size:{0}", queue.Size);
Random rand = new Random();
// Test1.1:顺序插入5个数据元素
for (int i = 0; i
C#数组和链表实现队列
标签:line csharp efault returns write har sharp city default
原文地址:https://www.cnblogs.com/sunliyuan/p/12985426.html
评论