1 function LinkedList(){ 2 var Node = function(element){ 3 this.element = element; 4 this.next = null; 5 }; 6 7 var length = 0; 8 var head = null 9 10 this.append = function(element){ 11 // 创建一个节点 12 var node = new Node(element); 13 var current = null; 14 15 if (head == null){ 16 head = node; 17 }else{ 18 current = head; 19 while(current.next){ 20 current = current.next; 21 } 22 //找到最后一项,将其next赋为node,建立连接 23 current.next = node; 24 } 25 length++; 26 } //向链表尾部添加一个新的项 27 28 this.insert = function (position, element) { 29 // 检查越界 30 if(position >= 0 && position < length){ 31 var node = new Node(element); 32 var current = head; 33 var previous = null 34 var index = 0 35 36 if(position === 0){ 37 node.next = current; 38 head = node; 39 }else{ 40 // 1 从前往后遍历找到position 41 while(index < position){ 42 previous = current; 43 current = previous.next; 44 index++; 45 } 46 47 //通过改变指针,将node链接在previous和current之间 48 previous.next = node; 49 node.next = current; 50 51 // 2 经验证1和2没有区别 52 //while (index++ < position) { 53 // previous = current; 54 // current = current.next; 55 //} 56 //通过改变指针,将node链接在previous和current之间 57 //node.next = current; 58 //previous.next = node; 59 return true; 60 } 61 }else{ 62 return false; 63 } 64 }; //向链表特定位置插入一个新的项 65 66 this.removeAt = function (position) { 67 if(position > -1 && position < length){ 68 var current = head; 69 var previous = null; 70 var index = 0; 71 72 if (position == 0){ 73 head = current.next; 74 }else{ 75 while(index < position){ 76 previous = current; 77 current = current.next; 78 index++; 79 } 80 previous.next = current.next; 81 } 82 length--; 83 return current.element; 84 }else{ 85 return null; 86 } 87 }; //从链表特定位置移除一项 88 this.remove = function (element) { 89 var index = this.indexOf(element); 90 this.removeAt(index); 91 }; //从链表中移除一项 92 this.indexOf = function (element) { 93 var current = head; 94 var index = 0; 95 while(current){ 96 if (current.element === element){ 97 return index; 98 } 99 current = current.next; 100 index++; 101 } 102 return -1; 103 }; //返回元素在链表中的索引,如果没有则返回-1 104 this.isEmpty = function () { 105 return length === 0; 106 }; //判断链表是否为空 107 this.size = function () { 108 return length; 109 }; //返回链表包含元素个数 110 this.getHead = function () { 111 return head; 112 }; //返回链表第一个元素 113 this.toString = function () { 114 var current = head; 115 var str = ""; 116 while(current){ 117 current = current.next; 118 str += "," + current.element; 119 } 120 return str.slice(1); 121 }; //只输出元素的值 122 this.print = function () { 123 console.log(this.toString()); 124 }; //打印元素的值 125 }