您的位置:首页 > 理论基础 > 数据结构算法

JavaScript数据结构与算法(一) 栈的实现

2017-06-08 15:34 316 查看
TypeScript版本源码

1 class Stack {
2     items = [];
3     public push(element) {
4         this.items.push(element);
5     }
6     public pop() {
7         return this.items.pop();
8     }
9     public peek() {
10         return this.items[this.items.length - 1];
11     }
12     public isEmpty() {
13         return this.items.length == 0;
14     }
15     public size() {
16         return this.items.length;
17     }
18     public clear() {
19         this.items = [];
20     }
21     public print() {
22         console.log(this.items.toString());
23     }
24 }


[b][b]TypeScript版本调用[/b][/b]

1 // 使用Stack类
2 // 验证一下栈是否为空
3 let stack = new Stack();
4 console.log(stack.isEmpty());       // => true
5
6 // 往栈添加元素
7 stack.push(5);
8 stack.push(8);
9
10 // 查看栈里添加的最后一位元素
11 console.log(stack.peek());          // => 8
12
13 // 再添加一个元素
14 stack.push(11);
15 console.log(stack.size());          // => 3
16 console.log(stack.isEmpty());       // => false
17
18 // 再添加一个元素
19 stack.push(15);
20
21 // 下图描绘目前我们对栈的操作,以及栈的当前状态



23 // 然后,调用两次pop方法从栈里移除2个元素:
24
25 stack.pop();
26 stack.pop();
27 console.log(stack.size());          // => 2
28 stack.print();                      // => [5,8]
29
30 // 下图描绘目前我们对栈的操作,以及栈的当前状态



[b]JavaScript版本源码[/b]

1 var Stack = (function () {
2     function Stack() {
3         this.items = [];
4     }
5     Stack.prototype.push = function (element) {
6         this.items.push(element);
7     };
8     Stack.prototype.pop = function () {
9         return this.items.pop();
10     };
11     Stack.prototype.peek = function () {
12         return this.items[this.items.length - 1];
13     };
14     Stack.prototype.isEmpty = function () {
15         return this.items.length == 0;
16     };
17     Stack.prototype.size = function () {
18         return this.items.length;
19     };
20     Stack.prototype.clear = function () {
21         this.items = [];
22     };
23     Stack.prototype.print = function () {
24         console.log(this.items.toString());
25     };
26     return Stack;
27 }());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: