JavaScript 实现常见数据结构 —— 栈与队列

本文详细介绍如何使用JavaScript数组方法扩展实现栈和队列两种基本数据结构。栈遵循后进先出(LIFO)原则,而队列遵循先进先出(FIFO)原则。通过具体代码示例,展示了栈的push、pop、top和empty方法,以及队列的push、pop、peek和empty方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈,是一种遵循后进先出(LIFO)原则的有序集合。

队列,是一种遵循先进先出(FIFO)原则的有序集合。

 

在 JavaScript 中,我们可以通过数组相关的方法很容易的扩展出这两种数据结构。

 

栈的 JavaScript 代码实现:

/**
 * Initialize your data structure here.
 */
var MyStack = function() {
    this._data = [];
};

/**
 * Push element x onto stack. 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this._data.push(x);
};

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function() {
    return this._data.pop();
};

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function() {
    return this._data[this._data.length -1];
};

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return this._data.length === 0;
};

/** 
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */

 

队列的 JavaScript 代码实现:

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
   this._queue = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this._queue.push(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    return this._queue.shift();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this._queue[0];
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this._queue.length === 0;
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */

 

转载于:https://www.cnblogs.com/mykiya/p/10959729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值