棧的特點(diǎn)及優(yōu)缺點(diǎn)
特點(diǎn):先進(jìn)后出,類似跌盤子,只能一個(gè)一個(gè)往上疊,取也只能一個(gè)接向下取;放到代碼里,類似與函數(shù)調(diào)用,一層接一層
實(shí)現(xiàn)方式:
封裝stack函數(shù);數(shù)據(jù)存與數(shù)組中,實(shí)現(xiàn)push;pop;peek:返回棧頂元素;isEmpty;clear;size;
以下代碼
function?Stack()?{
????????this.items?=?[];
????????this.length?=?0
????????Stack.prototype.push?=?function?(element)?{
????????????this.items.push(element)
????????????this.length?+=?1
????????????return?this.items
????????}
????????Stack.prototype.pop?=?function?()?{
????????????this.length?-=?1
????????????return?this.items.pop()
????????}
????????Stack.prototype.peek?=?function?()?{
????????????return?this.items[this.length?-?1]
????????}
????????Stack.prototype.isEmpty?=?function?()?{
????????????return?this.length?===?0
????????}
????????Stack.prototype.clear?=?function?()?{
????????????this.items?=?[]
????????????this.length?=?0
????????}
????????Stack.prototype.size?=?function?()?{
????????????return?this.length
????????}
????}
????var?stack?=?new?Stack()
????console.log(stack.push('a'))
????console.log(stack.push('b'))
????console.log(stack.push('c'))
????console.log(stack.push('d'))
????console.log(stack.push('e'))
????console.log(stack.pop())
????console.log(stack.peek())
????console.log(stack.isEmpty())
????console.log(stack.size())
????console.log(stack.clear())