栈是一种数据结构,其特点是先进后出,后进先出的一种特征。我们遇到只在一头操作,并且是采用先进后出,后进先出的原则,我们可以优先考虑栈结构。
顺序栈
function Stack() {
this.data = [];
this.count = 0;
}
Stack.prototype = {
push: function(element) {
this.data[this.count] = element;
++this.count;
return true;
},
pop: function() {
if (this.count == 0) return null;
var tmp = this.data[this.count - 1];
--this.count;
return tmp;
},
peek: function() {
return this.data[this.count - 1];
},
isEmpty: function() {
return this.count == 0;
},
size: function() {
return this.count;
},
print: function() {
let result = '';
for (let i of this.data) {
result = result + '=>' + i;
}
return result;
},
clear: function() {
this.count = 0;
}
}
Stack.prototype.constructor = Stack;
链式栈
function Node(data) {
this.data = data;
this.next = null;
}
function ListStack() {
this.head = new Node('head');
this.count = 0;
}
ListStack.prototype = {
push: function(element) {
var head = this.head;
var newNode = new Node(element);
newNode.next = head.next;
head.next = newNode;
++this.count;
},
pop: function() {
var head = this.head;
if (!head.next) return '节点不存在';
head.next = head.next.next;
--this.count;
return head.next;
},
peek: function() {
return this.head.next;
},
isEmpty: function() {
return this.count == 0;
},
size: function() {
return this.count;
},
print: function() {
var result = '';
var head = this.head;
while (head.next) {
result = result + '=>' + head.next
}
return result;
},
clear: function() {
this.count = 0;
this.head.next = null;
}
}