javascript单链表

<!doctype html>
<head>
	<meta charset = "utf-8" />
</head>

<body>
	<script>
		//单链表对象
		function createLinkList(){
			let first = null; //头指针
			let end = null; //尾指针
			let LinkList = {
				//构造空链表
				createEmpty : function(){
					//头结点
					first = {
						data : null,
						next : null
					};
					end = first;
				},
				//头插法建立单链表
				createByHead : function(arr){
					this.createEmpty();
					for(let i=0,len=arr.length; i<len; i++){
						first.next = {
							data : arr[i],
							next : first.next
						};
					}
				},
				//尾插法建立单链表
				createByEnd : function(arr){
					this.createEmpty();
					for(let i=0,len=arr.length; i<len; i++){
						end = end.next = {
							data : arr[i],
							next : null
						};
					}
				},
				//遍历
				printList : function(callback){
					for(let index = 1,p = first.next; p!=null; index++){
						callback.call(this,index,p.data);
						p = p.next;
					}
				},
				//插入 在第i个节点位置插入节点
				insert : function(i,value){
					//查找第i-1个节点
					let p = this.getNode(i-1);
					try{
						if(p==null) throw "该位置无法插入节点";
						else{
							p.next = {
								data : value,
								next : p.next
							} 
						}
						//如果p指向end,尾指针移动
						if(p == end){
							end = p.next;
						}
					}catch(err){
						console.log(err);
					}	
				},
				//获取第i个节点的引用
				getNode : function(i){
					let p = first, count = 0;
					while(p!=null && count<i){
						p = p.next;
						count++;
					}
					return p;
				},
				//计算表长
				getLength : function(){
					let p = first, length = 0;  
					while(p.next != null){
						p = p.next;
						length++;
					}
					return length;
				},
				//获取第i个节点的值
				getValue : function(i){
					let p = this.getNode(i);
					try{
						if(p==null) throw "没有该节点";
						else return p.data;
					}catch(err){
						console.log(err);
					}
				},
				//获取特定值所对应的序号
				getIndex : function(value){
					let p = first, count = 0;
					while(p != null){
						if(p.data == x) return count;
						p = p.next;
						count++;	
					}
					return count;
				}, 
				//删除第i个节点 返回被删节点的值
				delete : function(i){
					let p = this.getNode(i-1); //获取第i-1个节点
					try{
						//第i-1或i个节点不存在
						if(p==null || p.next==null) throw "节点不存在";
						else{
							let q = p.next,x = q.data;
							p.next = q.next;
							q = null;
							return x;
						}
					}catch(err){
						console.log(err);
					}
				},
				//删除全表
				deleteAll : function(){
					while(first != null){
						let q = first;
						first = first.next;
					}
					end = null;
				},
			}
			//自动执行一次创建空链表
			LinkList.createEmpty();
			
			return LinkList;
		}
		let LinkList = createLinkList();
		LinkList.printList(function(index,value){
			console.log("第"+index+"个节点的值是" + value);
		}); 
	</script>
</body>

</html>

  用createLinkList()中的LInkList对象作为链表对象,则createLinkList()就是其作用域。能形成私有变量的效果,因为first,end都是外部不可见的。而createLinkList()只要执行一次就可以了,则createEmpty()只执行一次,模拟了无参构造。

原文地址:https://www.cnblogs.com/githubMYL/p/8883355.html