栈,队列 in JavaScript
2021-05-17 15:31
标签:size return color .sh code div unshift class fun 栈,队列 in JavaScript 标签:size return color .sh code div unshift class fun 原文地址:https://www.cnblogs.com/xinfangzhang/p/9746395.html 1 // 在JavaScript里面,已经拥有push ,pop,shift,unshift的功能,但是,直接用太过简单。
2
3 // 队列
4 function Queue() {
5 var arr = [];
6 var size = 0;
7
8 var push = function(num) {
9 arr[size] = num;
10 size++;
11 };
12 var shift = function() {
13 var ret = arr[0];
14 for (var i = size-1;i>0;i--){
15 arr[i-1] = arr[i];
16 }
17 size--;
18 arr.length = size; // arr[size] = null;
19 return ret;
20 };
21 var get = function() {
22 return arr;
23 };
24
25 var length = function() {
26 return size;
27 };
28
29 return {
30 shift: shift,
31 push: push,
32 length: length,
33 get: get
34 };
35 };
36 var qu = new Queue();
37 qu.push(1);
38 qu.push(‘a‘);
39 qu.length(); //2
40 qu.get(); // [1, "a"]
41 qu.shift(); //1
42 qu.get(); //["a"]
43
44
45
46 // 栈
47 function Stock() {
48 var arr = [];
49 var size = 0;
50
51 this.push = function(num) {
52 arr[size] = num;
53 size++;
54 }
55 this.pop = function() {
56 var ret = arr[--size];
57 arr[size] = null; //or arr.length = size;
59 return ret;
60 }
61 this.length = function() {
62 return size;
63 }
64 this.get = function() {
65 return arr;
66 }
67 };
68 var st = new Stock();
下一篇:操作系统多线程多进程
文章标题:栈,队列 in JavaScript
文章链接:http://soscw.com/index.php/essay/86781.html