function Node(value) {
this.data = value;
this.next = null;
}
function LinkedStack() {
this.head = null;
this._length = 0;
this.clear = function () {
this.head = null;
this._length = 0;
};
this.empty = function () {
return this.head === null;
};
this.get = function () {
if (this.empty()) {
throw new Error("栈为空");
}
return this.head.data;
};
this.push = function (value) {
const new_node = new Node(value);
if (!this.empty()) {
new_node.next = this.head;
}
this.head = new_node;
this._length++;
};
this.pop = function () {
if (this.empty()) {
throw new Error("栈为空");
}
const data = this.head.data;
this.head = this.head.next;
this._length--;
return data;
};
this.length = function () {
return this._length;
};
}
stack = new LinkedStack();
stack.push(10);
stack.push(9);
stack.push(8);
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.length())
console.log(stack.get())
【数据结构连载一栈】【链式存储栈】javascript
最新推荐文章于 2024-10-02 05:39:15 发布