代码改变世界

js模拟链表

2018-06-19 11:48  muamaker  阅读(585)  评论(0编辑  收藏  举报

链表: 每个元素,都有一个指针,指向下一个元素

		//链表
		function LinkedList(){
			var head = null;
			length = 0;
			
			this.append = function(ele){
					var cnode = {
						ele:ele,
						next:null
					};
					if(head === null){
						head = cnode;
					}else{
						//追加到节点
						var current = head;
						while(current.next){
							current = current.next;
						}
						current.next = cnode;
					}
					length++;
				};
				
			this.removeAt = function(pos){
					//删除第几个元素
					//检查越界
					if(pos > -1 && pos < length){
						var current = head,
						previous,
						index = 0;
						//移除第一项
						if(pos == 0){
							head = current.next;
						}else{
							while(index++ < pos){
								previous = current;
								current = current.next;
							}
							//前面的next,指向当前项的next,即干掉当前项
							previous.next = current.next;
						}
						length--;
						return current.ele;
					}else{
						return null;
					}
				};
			this.insert = function(pos,ele){
					if(pos >= 0 && pos <= length){
						var nodes = {
							ele:ele,
							next:null
						};
						var current = head,
						previous,
						index = 0;
						if(pos == 0){
							//第一项插入
							nodes.next = current;
							head = nodes;
						}else{
							while(index++ < pos){
								previous = current;
								current = current.next;
							}
							nodes.next  = current;
							previous.next = nodes;
						}
						length++;
						return true;
					}else{
						return false;
					}
				};
			this.indexOf = function	(ele){
					var current = head;
					var index = -1;
					while(current){
						index++;
						if(current.ele ===  ele){
							return index;
						}
						current = current.next;
					}
					return -1;
			};
			
			this.remove = function(ele){
					var index = this.indexOf(ele);
					return this.removeAt(index);
			};
			this.toString = function(){
					var current = head;
					var str = '';
					var index = 0;
					while(current){
						str = str + current.ele+"-"  + index + "\n";   
						index++;	
						current = current.next;
					}
					console.log(str);
			};
			this.size = function(){
				return length;
			};
			this.isEmpty = function(){
				return !length;
			}
			this.getHead = function(){
				return head;
			}

		}
			

		var list = new LinkedList();
		list.append("a");
		list.append("b");
		list.append("c");
		list.insert(2,"bgb");
		list.append("d");
		list.append("大大");
		list.toString();
		list.remove("c");