码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Stack

时间:2016-01-12 22:45:46      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

function Stack() {
	var items = [];
	this.push = function(item) {
		items.push(item)
	}
	this.pop = function() {
		return items.pop()
	}
	this.peek = function() {
		return items[items.length - 1]
	}
	this.isEmpty = function() {
		return items.length == 0
	}
	this.size = function() {
		return items.length
	}
	this.clear = function() {
		items = []
	}
	this.printf = function() {
		console.log(items.toString())
	}
	this.divideBy2 = function(decNumber) {
		var remStack = new Stack(),
		rem,
		binaryString = ‘‘;
		while (decNumber > 0) {
			rem = Math.floor(decNumber % 2);
			remStack.push(rem);
			decNumber = Math.floor(decNumber / 2)
		}
		while (!remStack.isEmpty()) {
			binaryString += remStack.pop().toString()
		}
		return binaryString
	}
}
var stacks = new Stack();
console.log(stacks.isEmpty());
stacks.push(5);
stacks.push(4);
console.log(stacks.peek());
stacks.push(11);
console.log(stacks.size());
console.log(stacks.isEmpty());
stacks.push(15);
stacks.pop();
console.log(stacks.size());
stacks.printf();
console.log(stacks.divideBy2(33));

  

JavaScript Stack

标签:

原文地址:http://www.cnblogs.com/shidengyun/p/5125744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!