JS常用数据结构和算法--链表
链表
头指针,总是指向的链表的第一个节点(链表里已有节点),当指针指向的元素并不存在,默认为null(空)。
function LinkedList(){ /*Node表示链表上的节点,element 代表结点上的元素,next代表姐结点 里指向下一个结点的指针*/ var Node = function (element) { this.element = element; this.next = null; } //链表的长度 var length = 0; //头指针 var head = null; //在列表尾部添加新项 this.append = function(element) { let node = new Node(element); //判断链表头指针是否指向有节点 if(head === null) { head = node; } else { let current = head; while (current.next) { current = current.next; } current.next = node; } length++; } //在链表特定位置移除某一元素 this.removeAt = function (pos) { if(pos > -1 && pos < length){ let current= head; let previous = head; let index = 0; //移除第一项 if(pos === 0) { head = current.next; } else { while(index++ < pos) { previous = current; current = current.next; } //将pevious与current的下一项链接起来,跳过current previous.next = current.next; } length--; return current.element; } else { return null } } //返回元素在列表中的索引(位置).如果列表中没有该元素则返回-1 this.indexOf = function (element) { let current = head; let index = 0; while(current) { if(element === current.element) { return index; } index++; current = current.next; } return -1; } //链表中移除某一节点 this.remove = function(element) { let index = this.indexOf(element); return this.removeAt(index); } //链表元素是否为空 this.isEmpty = function() { return length === 0; } //返回链表长度 this.size = function() { return length } //链表字符串输出 this.toString = function () { let current = head; let string = ; while(current) { string += +current.element; current = current.next; } return string; } } var linkedList = new LinkedList(); linkedList.append(1); linkedList.append(2); linkedList.append(3); console.log(linkedList.indexOf(3)); linkedList.removeAt(1); console.log(linkedList.toString());
输出结果如下