JS实现队列
JS实现队列:
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头
链式队列的实现
function LinkedQueue() { let Node = function (ele) { this.ele = ele; this.next = null; } let length = 0, front, //队首指针 rear; //队尾指针 this.push = function (ele) { let node = new Node(ele), temp; if (length == 0) { front = node; } else { temp = rear; temp.next = node; } rear = node; length++; return true; } this.pop = function () { let temp = front; front = front.next length--; temp.next = null return temp; } this.size = function () { return length; } this.getFront = function () { return front; // 有没有什么思路只获取队列的头结点,而不是获取整个队列 } this.getRear = function () { return rear; } this.toString = function () { let string = '', temp = front; while (temp) { string += temp.ele + ' '; temp = temp.next; } return string; } this.clear = function () { front = null; rear = null; length = 0; return true; } } let myQueue = new LinkedQueue(); myQueue.push(1) myQueue.push(2) myQueue.push(3) myQueue.push(4) console.log(myQueue.toString()) // 1 2 3 4 console.log(myQueue.pop()) // Node { ele: 1, next: null } console.log(myQueue.toString()) // 2 3 4
顺序存储队列:利用js内置Array对象
function ArrayQueue(){ var arr = []; //入队操作 this.push = function(element){ arr.push(element); return true; } //出队操作 this.pop = function(){ return arr.shift(); } //获取队首 this.getFront = function(){ return arr[0]; } //获取队尾 this.getRear = function(){ return arr[arr.length - 1] } //清空队列 this.clear = function(){ arr = []; } //获取队长 this.size = function(){ return length; } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步