数据结构JavaScript描述(一)

来源:互联网 发布:侠义 知乎 编辑:程序博客网 时间:2024/06/06 22:51

本文主要用JavaScript实现一些常用的数据结构,并带上相应的讲解,其中的代码并发所有都由本人所写,只是出于学习目的,在此分享出来,并带上一定的解释,以便大家学习。

相应的数据结构有:

  • 队列
  • 单链表
  • 双向链表
  • 二叉树

相应代码已上传GitHub地址:https://github.com/HolyZheng/-JavaScript- 。

本文先给大家介绍队列和栈,其他的在后续的文章中给大家带来。


队列

队列 的概念应该不用多说了吧,一句话:先进先出(first in first out),就跟我们平时排队一样,先排队的就先到。

代码实现:

/** *       使用javascript实现一个队列 *       具有enqueue、dequeue、show三个方法 */function Queue () {    this._oldestIndex = 1;    this._newestIndex = 1;    this._storage = {};}Queue.prototype.size = function () {    return this._newestIndex - this._oldestIndex;}Queue.prototype.enqueue = function (data) {    this._storage[this._newestIndex] = data;    this._newestIndex++;}Queue.prototype.dequeue = function () {    var oldestIndex = this._oldestIndex,        newestIndex = this._newestIndex,        deletedData;    if (oldestIndex !== newestIndex) {        deletedData = this._storage[oldestIndex];        delete this._storage[oldestIndex];        this._oldestIndex++;        return deletedData;    }    return;}Queue.prototype.show = function () {    console.log(this._storage);}

这个队列主要有三个方法:enqueue、dequeue、show,分别为入队,出队,查看队列。
enqueue跟show都很简单,相信这里不用我来讲,大家一看就能懂,所以就讲一下dequeue函数:

enqueue 函数:

Queue.prototype.dequeue = function () {    var oldestIndex = this._oldestIndex,  //记录队头位置        newestIndex = this._newestIndex,  //记录队尾位置        deletedData;                      //记录要删除的数据,并返回。    if (oldestIndex !== newestIndex) {        deletedData = this._storage[oldestIndex];        delete this._storage[oldestIndex];        this._oldestIndex++;        return deletedData;    }    return;}

删除元素的时候,只需要用先判断队列是否为空了,如果不空就用 delete 方法把相应的对象属性删除,然后对头位置加一就行了。

跟队列就刚好相反,“先进后出”,就像往桶里放球,后面放的在上方,可以先拿到。

代码实现:

/** *       使用javascript实现一个栈 *       具有push、pop、show三个方法 */function Stack () {    this._size = 0;    this._storage = {};}Stack.prototype.push = function (data) {    var size = ++this._size;    this._storage[size] = data;}Stack.prototype.pop = function () {    var size = this._size;    var deletedData;    if (size) {        deletedData = this._storage[size];        delete this._storage[size];        this._size--;        return deletedData;    }}Stack.prototype.show = function () {    var len = 1;    while (len <= this._size) {        console.log(this._storage[len]);        len++;    }}var stackA = new Stack();

这个 栈 主要有三个方法:push、pop、show 三个方法,同样我们挑一个相对较难的方法来讲一下:

Stack.prototype.pop = function () {    var size = this._size; //指向栈头    var deletedData;    if (size) {        deletedData = this._storage[size];        delete this._storage[size];        this._size--;        return deletedData;    }}

pop 元素的时候,先判断栈是否为空,如果不为空的话,就 delete 掉栈头的元素,即最上方最先拿到的元素,然后this._size –指向下一个元素。


总结

  • 队列,先进先出,就像我们平时排队
  • 栈,先进后出,就像往桶里放球,后放的在上方,可以先拿到

因为队列和栈相对简单,所以本文篇幅比较短,下一篇文章我会为大家带来难度高一点的 单链表双向链表 的代码实现和讲解,文章也会相对详细,欢迎大家关注。

阅读全文
0 0
原创粉丝点击