js实现链式栈的代码实例

不言
不言 原创
2018-08-18 16:34:29 940浏览

本篇文章给大家带来的内容是关于js实现链式栈的代码实例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

官方定义:链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。

具体的实现

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function LinkStack(){
				this.length = 0;
				this.top = null;//栈顶指针				
			};
			
			LinkStack.prototype.Node = function(el){
				this.element = el;
				this.next = null;
			};
			
			//压栈
			LinkStack.prototype.push = function(el){
				var current,
				   Node = this.Node,
				   node = new Node(el);
				   
				  if(!this.top){
				  	this.top = node;
				  	this.length++;
				  	return true;
				  }else{
				  	current = this.top; 
				  	node.next = current;
				  	
				  	this.top = node;
				  	this.length++;
				  	return true;
				  }
			};
			
			//退栈
			LinkStack.prototype.pop = function(){
				var current = this.top;
				if(current){
					this.top = current.next;
					current.next = null;
					this.length--;
					return current;
				}else{
					throw "error null stack"
				}
			};
			
			LinkStack.prototype.toString = function(){
				var str = "",
				    current = this.top;
				
				while(current){
					str += current.element + " ";
					current = current.next;
				}
				
				return str;
			};
			
			//清空栈
			LinkStack.prototype.clear = function(){
				this.top = null;
				this.length = 0;
				return true;
			};
			
			
			/***************测试代码******************/
			function test(){
				var linkStack = new LinkStack();
				
				//压栈
				for(var i=1;i<21;i++){
					linkStack.push(i);
				}
				console.log("压栈->" + linkStack.toString());
				
				//退栈
				linkStack.pop();
				linkStack.pop();
				linkStack.pop();
				console.log("退栈->" + linkStack.toString());
				
				//清空栈
				linkStack.clear();
				console.log("清空栈->" + linkStack.toString());
				
			}
			
			test();
		</script>
	</head>
	<body>
	</body>
</html>

相关推荐:

js的代码如何进行压缩?js代码压缩的简单方法

Nodejs中buffer是什么?Nodejs中buffer类的用法

以上就是js实现链式栈的代码实例的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。