[js]①栈和队列~1、堆栈--数据结构回忆小笔记

来源:互联网 发布:谢津死亡真相知乎 编辑:程序博客网 时间:2024/06/01 07:29

1、用JQ实现堆栈。

堆栈进行的是先进后出的操作



<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><script src="../../../H5/jquery-3.1.1.min.js"></script><title>Document</title><script>$(function(){function initStack(){this.head = -1;//设置头部this.tail = -1;//设置尾部this.arr = new Array();//压栈this.pushStack = function(num){this.head++;this.arr[this.head] = num;}//出栈this.popStack = function(){if(this.isempty()){console.log("堆栈为空!!")}else{this.arr[this.head] = null;this.head--;}}//判断栈是否为空this.isempty = function(){if(this.head == this.tail){return true;}elsereturn false;}//删除栈this.del = function(){if(this.isempty()){console.log("没东西让你删了!!")}else{while(!this.isempty()){this.popStack();}}}}var one = new initStack();$("#push").click(function(event) {one.pushStack($('#num').val());$('#display').text(one.arr);});$("#pop").click(function(event) {one.popStack();$('#display').text(one.arr);});$("#del").click(function(event) {one.del();$('#display').text(one.arr);});})</script><style>*{margin: 0;padding: 0;}</style></head><body><form action=""><input type="text" id="num"><input type="button" value="压栈" id="push"><input type="button" value="出栈" id="pop"><input type="button" value="删除" id="del"></form><div id="display"></div></body></html>

之所以使用js这种语言,纯粹是为了锻炼自己在不同语言环境下的适应能力~~



<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><script src="../../../H5/jquery-3.1.1.min.js"></script><title>Document</title><script>$(function(){function initStack(){this.head = -1;//设置头部this.tail = -1;//设置尾部this.arr = new Array();//压栈this.pushStack = function(num){this.head++;this.arr[this.head] = num;}//出栈this.popStack = function(){if(this.isempty()){console.log("堆栈为空!!")}else{this.arr[this.head] = null;this.head--;}}//判断栈是否为空this.isempty = function(){if(this.head == this.tail){return true;}elsereturn false;}//删除栈this.del = function(){if(this.isempty()){console.log("没东西让你删了!!")}else{while(!this.isempty()){this.popStack();}}}}var one = new initStack();$("#push").click(function(event) {one.pushStack($('#num').val());$('#display').text(one.arr);});$("#pop").click(function(event) {one.popStack();$('#display').text(one.arr);});$("#del").click(function(event) {one.del();$('#display').text(one.arr);});})</script><style>*{margin: 0;padding: 0;}</style></head><body><form action=""><input type="text" id="num"><input type="button" value="压栈" id="push"><input type="button" value="出栈" id="pop"><input type="button" value="删除" id="del"></form><div id="display"></div></body></html>