0
点赞
收藏
分享

微信扫一扫

数据结构与算法(js描述)———— 栈

逸省 2022-04-01 阅读 75

文章目录


前言

本文对JavaScript描述的栈类型数据结构总结。


一、栈是什么?

栈就是和列表类似的一种数据结构,是一种高效的数据结构,因为数据只能在栈顶添加或删除。

二、栈的实现

function Stack() {
	this.dataStore = []; //保存栈内元素
	this.top = 0;	//记录栈顶位置
	this.push = push; //向栈内压入新元素
	this.pop = pop;	//移除栈顶元素
	this.peek = peek; //返回栈顶元素
	this.length = length; //栈内元素个数
	this.clear = clear; //清空栈
}

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

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

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

function length() {
	return this.top;
}

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

2.数制转换

//设计将数字转化为二至九进制
function mulBase() {
	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
}

3.判断回文

回文:指一个单词、短语或数字,从前往后写和从后往前写都是一样的。

//判断给定字符串是否为回文
function isPalindrome() {
	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 true;
	}
	else {
		return false;
	}
}

4.递归演示

//计算任何数字的阶乘
function factorial(n) {
	if (n === 0) {
		return 1
	}
	else {
		return n * factorial(n-1);
	}
}

//使用栈模拟递归过程
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;
}

总结

	下一篇JavaScript描述的队列数据类型
举报

相关推荐

0 条评论