C# Queue 和Stack的实现
Queue 和Stack的使用就不用多说吧,一个是先进先出,一个是后进先出。 这里我主要关注其实现原理。
queue的实现如下:
public class Queue<T> : IEnumerable<T>,System.Collections.ICollection,IReadOnlyCollection<T> {
private T[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
public Queue(int capacity) {
if (capacity < )
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNumRequired);
_array = new T[capacity];
_head = ;
_tail = ;
_size = ;
}
public Queue(IEnumerable<T> collection)
{
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
_array = new T[_DefaultCapacity];
_size = ;
_version = ;
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Enqueue(en.Current);
}
}
}
public void Enqueue(T item) {
if (_size == _array.Length) {
int newcapacity = (int)((long)_array.Length * (long)_GrowFactor / );
if (newcapacity < _array.Length + _MinimumGrow) {
newcapacity = _array.Length + _MinimumGrow;
}
SetCapacity(newcapacity);
}
_array[_tail] = item;
_tail = (_tail + ) % _array.Length;
_size++;
_version++;
}
public T Dequeue() {
if (_size == )
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyQueue);
T removed = _array[_head];
_array[_head] = default(T);
_head = (_head + ) % _array.Length;
_size--;
_version++;
return removed;
}
public bool Contains(T item) {
int index = _head;
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > ) {
if (((Object) item) == null) {
if (((Object) _array[index]) == null)
return true;
}
else if (_array[index] != null && c.Equals(_array[index], item)) {
return true;
}
index = (index + ) % _array.Length;
}
return false;
}
private void SetCapacity(int capacity) {
T[] newarray = new T[capacity];
if (_size > ) {
if (_head < _tail) {
Array.Copy(_array, _head, newarray, , _size);
} else {
Array.Copy(_array, _head, newarray, , _array.Length - _head);
Array.Copy(_array, , newarray, _array.Length - _head, _tail);
}
}
_array = newarray;
_head = ;
_tail = (_size == capacity) ? : _size;
_version++;
}
}
Stack的实现:
public class Stack<T> : IEnumerable<T>, System.Collections.ICollection,IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements
private int _size; // Number of items in the stack. public Stack(int capacity) {
if (capacity < )
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNumRequired);
_array = new T[capacity];
_size = ;
_version = ;
} public Stack(IEnumerable<T> collection)
{
if (collection==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
_array = new T[count];
c.CopyTo(_array, );
_size = count;
}
else {
_size = ;
_array = new T[_defaultCapacity]; using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Push(en.Current);
}
}
}
} public void Push(T item) {
if (_size == _array.Length) {
T[] newArray = new T[(_array.Length == ) ? _defaultCapacity : *_array.Length];
Array.Copy(_array, , newArray, , _size);
_array = newArray;
}
_array[_size++] = item;
_version++;
} public T Pop() {
if (_size == )
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);
_version++;
T item = _array[--_size];
_array[_size] = default(T); // Free memory quicker.
return item;
} public bool Contains(T item) {
int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > ) {
if (((Object) item) == null) {
if (((Object) _array[count]) == null)
return true;
}
else if (_array[count] != null && c.Equals(_array[count], item) ) {
return true;
}
}
return false;
}
}
Queue 和Stack都是依靠数组来实现,并且都有带int capacity的构造函数。假如我们定义一个数组长度为5,Queue 和Stack都添加了5个元素,现在需要移除2个元素,Queue 移除arr[0],arr[1]两个元素(移除通过下标_head+1完成的),Stack移除arr[4],arr[3]两个元素(通过_size-1完成的),现在再添加2个元素,Queue 的arr5个元素都已被占用,需要创建新的数组,并且把原先3,4,5个元素拷贝到新的数组里面,但是Stack就好很多,新增加的元素可以直接赋值到arr[3],arr[4],查找Contains方法的实现都是循环数组arr里面的每个元素
C# Queue 和Stack的实现的更多相关文章
- Scala 深入浅出实战经典 第39讲:ListBuffer、ArrayBuffer、Queue、Stack操作代码实战
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- C++关于vector、queue、stack、priority_queue的元素访问
vector.queue.stack.priority_queue对元素进行元素访问时,返回的是对应元素的引用.
- ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借
ASP.NET MVC深入浅出系列(持续更新) 一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...
- 数据结构与算法(4) -- list、queue以及stack
今天主要给大家介绍几种数据结构,这几种数据结构在实现原理上较为类似,我习惯称之为类list的容器.具体有list.stack以及queue. list的节点Node 首先介绍下node,也就是组成li ...
- C#10在List, Queue 以及Stack中使用EnsureCapacity方法来提升性能
简介 在今天的文章中,我们将介绍 C# 10 中引入的一项新功能.这是已添加到 List.Queue 和 Stack 集合中的 EnsureCapacity 方法.我们将讨论为什么我们应该使用这个方法 ...
- deque、queue和stack深度探索(下)
deque如何模拟连续空间?通过源码可以看到这个模型就是通过迭代器来完成. 迭代器通过重载操作符+,-,++,--,*和->来实现deque连续的假象,如上图中的 finish-start ,它 ...
- Queue及Stack
Queue 她是一个接口,有多冢实现方式(LinkedList.ArrayDeque等) 类别 方法 入队 add.offer(优先级高) 出队 remove.poll 查询 element.peek ...
- Map、Set、List、Queue、Stack的特点与用法
Collection 接口的接口 对象的集合 ├ List 子接口 按进入先后有序保存 可重复 │├ LinkedList ...
- .NET中的Queue和Stack
1.ArrayList类 ArrayList类主要用于对一个数组中的元素进行各种处理.在ArrayList中主要使用Add.Remove.RemoveAt.Insert四个方法对栈进行操作.Add方法 ...
随机推荐
- JDBC辅助类封装 及应用
一:代码图解: 二:配置文件: driverClassName=com.mysql.jdbc.Driver url=jdbc\:mysql\://127.0.0.1\:3306/xlzj_sh_new ...
- LeetCode(60): 第k个排列
Medium! 题目描述: 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列. 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: "123" ...
- Deep Learning系统实训之三:卷积神经网络
边界填充(padding):卷积过程中,越靠近图片中间位置的像素点越容易被卷积计算多次,越靠近边缘的像素点被卷积计算的次数越少,填充就是为了使原来边缘像素点的位置变得相对靠近中部,而我们又不想让填充的 ...
- Java8 容器类详解
ArrayList Vector CopyOnWriteArrayList LinkedList HashMap ConcurrentHashMap LinkedHashMap 使用场景 随机访问 ...
- python 全栈开发,Day126(创业故事,软件部需求,内容采集,显示内容图文列表,MongoDB数据导入导出JSON)
作业讲解 下载代码: HBuilder APP和flask后端登录 链接:https://pan.baidu.com/s/1eBwd1sVXTNLdHwKRM2-ytg 密码:4pcw 如何打开APP ...
- python 全栈开发,Day15(递归函数,二分查找法)
一.递归函数 江湖上流传这这样一句话叫做:人理解循环,神理解递归.所以你可别小看了递归函数,很多人被拦在大神的门槛外这么多年,就是因为没能领悟递归的真谛. 递归函数:在一个函数里执行再调用这个函数本身 ...
- Redis设置Key/value的规则定义和注意事项(附工具类)
对于redis的存储key/value键值对,经过多次踩坑之后,我们总结了一套规则:这篇文章主要讲解定义key/value键值对时的定义规则和注意事项. 前面一篇文章讲了如何定义Redis的客户端和D ...
- Web前端开发最佳实践(13):前端页面卡顿?可能是DOM操作惹的祸,你需要优化代码
文档对象模型(DOM)是一个独立于特定语言的应用程序接口.在浏览器中,DOM接口是以JavaScript语言实现的,通过JavaScript来操作浏览器页面中的元素,这使得DOM成为了JavaScri ...
- 2015 Benelux Algorithm Programming Contest E-Excellent Engineers
题目大意:有n个人,每个人都有三个物品,排名分别为a[ i ],b[ i ],b[ i ],现在要删掉其中的一些人 如果一个人x的三个物品的排名为a[ x ],b[ x ],b[ x ],若存在另一个 ...
- P1541 乌龟棋 线性dp
题目背景 小明过生日的时候,爸爸送给他一副乌龟棋当作礼物. 题目描述 乌龟棋的棋盘是一行NN个格子,每个格子上一个分数(非负整数).棋盘第1格是唯一的起点,第NN格是终点,游戏要求玩家控制一个乌龟棋子 ...