javaScript实现栈数据结构

前言

对于编程基础,算法和数据结构是必不可少的知识,这里简单用 javaScript 语言来实现基本的数据结构。

用 javaScript 中的线性表数组来模拟实现

使用函数的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function Stack() {
var stack = []
this.push = element => stack.push(element)
this.pop = () => stack.pop()
this.length = () => stack.length
this.top = () => {
if (stack.length) {
return stack[stack.length - 1]
}
return 'stack empty'
}
this.clear = () => {
stack.length = 0
return true
}
this.toString = () => {
if (stack.length) {
stack.reverse()
return stack.join(' ')
}
return 'stack empty'
}
}

使用 class 类的方式

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

使用链表来模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function LinkedStack() {
var top
var length = 0
function Node(element) {
this.element = element
this.next = null
}
this.push = function (element) {
var node = new Node(element)
if (top) {
node.next = top
top = node
length++
return true
} else {
top = node
length++
return true
}
}
this.pop = function () {
if (top) {
var current
current = top
top = top.next
current.next = null
length--
return current
} else {
return 'stack empty'
}
}
this.top = function () {
return top
}
this.length = function () {
return length
}
this.toString = function () {
var string = ''
var current = top
while (current) {
string += current.element
current = current.next
}
return string
}
this.clear = function () {
top = null
length = 0
return true
}
}
-------------本文结束感谢您的阅读-------------

本文标题:javaScript实现栈数据结构

文章作者:Water

发布时间:2020年05月08日 - 14:05

最后更新:2023年08月01日 - 06:08

原始链接:https://water.buging.cn/2020/05/08/javaScript实现栈数据结构/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!