<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>链表操作</title> </head> <body> <script> function LinkList() { function Node(data) { this.data = data; this.next = null; } //属性 this.head = null; this.length = 0; LinkList.prototype.append = function (data) { //创建新的节点 var newNode = new Node(data); if (this.length == 0) { this.head = newNode; } else { var current = this.head; while (current.next) { current = current.next; } current.next = newNode; } this.length += 1; }; //toString() LinkList.prototype.toString = function () { //定义变量 var current = this.head; // var listString = ""; while (current) { listString += current.data + " "; current = current.next; } return listString; }; //insert方法 LinkList.prototype.toString = function (position, data) { if (position < 0 || position > this.length) return false; //根据data创建节点 var newNode = new Node(data); // if (position == 0) { newNode.next = this.head; this.head = newNode; } else { var index = 0; var current = head; var previous = null; while (index++ < position) { previous = current; current = current.next; } newNode.next = current; previous.next = newNode; } this.length++; return true; }; //获取详情方法 LinkList.prototype.get = function (position) { if (position < 0 || position >= this.length) return null; //获取对应的data var current = this.head; var index = 0; while (index < position) { current = current.next; } return current.data; }; LinkList.prototype.get = function (data) { var current = this.head; var index = 0; //开始查找 while (current) { if (current.data == data) { return index; } current = current.next; index += 1; } return -1; }; //update方法 //获取详情方法 LinkList.prototype.update = function (position, newData) { if (position < 0 || position >= this.length) return false; //获取对应的data var current = this.head; var index = 0; while (index++ < position) { current = current.next; } //将数据替换 current.data = newData; return true; }; //从列表的特定位置删除1项 LinkList.prototype.removeAt = function (position) { if (position < 0 || position >= this.length) return false; var current = this.head; //判断是否删除的是第一个节点 if (position == 0) { this.head = this.head.next; } else { var index = 0; var previous = null; while (index++ < position) { previous = current; current = current.next; } previous.next = current.next; } this.length -= 1; return current.data; }; LinkList.prototype.remove = function (data) { var position=this.indexOf(data) return this.removeAt(position) } } </script> </body> </html>