链栈的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>

猜你喜欢

转载自blog.csdn.net/Kuyin328178972/article/details/81779970