JavaScript中的栈及通过栈操作的实例

<script>
		/*栈操作*/
		function Stack() {
			this.dataStore = [];
			this.top = 0;

			this.push = push;
			this.pop = pop;
			this.peek = peek;
			this.clear = clear;
			this.length = length;
		}

		function push(ele) {
			this.dataStore[this.top ++] = ele;
		}

		function peek() {
		    return this.dataStore[this.top - 1];
		}

		function pop() {
			return this.dataStore[-- this.top];
		}

		function clear() {
			this.top = 0;
		}

		function length() {
			return this.top;
		}

		var s = new Stack();
		s.push('Han');
		s.push('hansome');
		s.push('zhang');
		console.log(s.length());//3
		console.log(s.peek());//zhang
		console.log(s.pop());//zhang
		console.log(s.length());//2
		console.log(s.clear());//undefined
		console.log(s.length());//0

		// 1.数制之间的相互转换
		function mulBase(num, base) {
			var s = new Stack();
			do {
				s.push(num % base);
				num = Math.floor(num /= base);
			} while (num > 0);
			var converted = "";
			while(s.length() > 0) {
				converted += s.pop();
			}
			return converted;
		}
		var num = 32;
		var base = 2;
		console.log(mulBase(num, base));//100000
		// 2.判断字符串是否是回文
		function isPalindrome(word) {
			var s = new Stack();
			for (var i = 0; i < word.length; i++) {
				s.push(word[i]);
			}
			var rword = "";
			while(s.length() > 0) {
				rword += s.pop();
			}
			if (word == rword) {
				return "是回文!";
			}else {
				return "不是回文!";
			}
		}
		console.log(isPalindrome("helccleh"));//是回文
		console.log(isPalindrome('abc'));//不是回文
		// 3.使用栈来模拟递归过程
		function fact(n) {
			var s = new Stack();
			while(n > 1) {
				s.push(n --);
			}
			var product = 1;
			while (s.length() > 0) {
				product *= s.pop();
			}
			return product;
		}
		console.log(fact(6));//720
	</script>

  

posted @ 2016-12-11 20:31  HandsomeHan  阅读(292)  评论(0编辑  收藏  举报