JavaScript实现栈、队列、链表

栈:后进先出;栈顶(表尾)移除,栈顶添加,只能访问栈顶元素(peek方法);

function stack(){
    		var items=[];
    		this.push=function(ele){//添加,注意不返回新数组的长度;
    			 items.push(ele);
    		};
    		this.pop=function(ele){//移除栈顶元素并且返回被移除的元素
    			return items.pop(ele);
    		};
    		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.print=function(){//辅助方法实现把栈里的元素都输出到控制台
    			console.log(items.toString());
    		}
    	}

队列:先进先出;在队首移除,队尾添加;

    	function Queue(){
    		var items=[];
    		this.enqueue=function(ele){
    			items.push(ele);
    		};
    		this.dequeue=function(ele){
    			return items.shift(ele);
    		};
    		this.font=function(){
    			return items[0];
    		}
    		this.isEmpty=function(){
    			return items.length==0;
    		};
    		this.clear=function(){
    			 items=[];
    		};
    		this.size=function(){
    			 return items.length;
    		};
    		this.print=function(){
    			console.log(items.toString());
    		};
    	}
    	var myQueue=new Queue();
    	myQueue.enqueue("tom");
    	myQueue.enqueue("jack");
    	myQueue.print();
    	myQueue.dequeue();
    	myQueue.print();

链表:不同于固定长度的数组,链表中的元素都不连续放置;每个元素组成:存储元素本身的节点、指向下一个元素的指针。添加和删除不需要移动其他元素;

关于链表的头结点:头结点是第一结点,只是一般没有数据。头结点后面是首元结点,即第一个存放数据的结点,做删除操作时,一般需要返回所删除结点的数据,所以一般不删除头结点。

function Node(element) {
   this.element = element;
   this.next = null;
}

function LList() {
   this.head = new Node("head");
   this.size=0;
   this.find =function(item) {
	   var currNode = this.head;
	   while (currNode.element != item) {
	      currNode = currNode.next;
	   }
	   return currNode;
	};
   this.insert =function(newElement, item) {
	   var newNode = new Node(newElement);
	   var current = this.find(item);
	   newNode.next = current.next;
	   current.next = newNode;
	   this.size++;
	};
   this.findPrevious =function(item) {
	   var currNode = this.head;
	   while ((currNode.next) && 
	           (currNode.next.element != item)) {
	      currNode = currNode.next;
	   }
	   return currNode;
	};
   this.remove =function(item) {
	   var prevNode = this.findPrevious(item);
	   if ((prevNode.next)) {
	       prevNode.next = prevNode.next.next;
	   }
	   this.size--;
	};
}
   

var cities = new LList();
cities.insert("Conway", "head");
cities.insert("Russellville", "Conway");
cities.insert("Carlisle", "Russellville");
cities.insert("Alma", "Carlisle");
console.log(cities);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值