标签:link color head eth 功能测试 获取 function move rev
用JS实现一个简单的单向链表,并完成相关的功能
1 //创建一个Node辅助类,用来生成节点 2 function Node(value) { 3 this.value = value; 4 this.next = null; 5 } 6 7 //链表类 8 function LinkedList() { 9 this.head = null; 10 this.length = 0; 11 //向链表尾部追加元素 12 this.push = push; 13 //从链表中查找某个元素 14 this.find = find; 15 //在链表中任意一个元素之后插入一个元素 16 this.insertAfter = insertAfter; 17 //从链表中查找任意元素节点的前一个节点 18 this.findPrevious = findPrevious; 19 //从链表中删除值为value的元素 20 this.remove = remove; 21 //返回当前链表的长度 22 this.size = size; 23 //查找某个元素在链表中的索引值 24 this.indexof = indexof; 25 //删除链表中第pos个元素 26 this.removeAt = removeAt; 27 //获取链表中第一个元素 28 this.getHead = getHead; 29 //打印当前的链表,供测试用 30 this.print = print; 31 }
function push(value) { var node = new Node(value); if (this.head == null) { this.head = node; } else { var current = this.head; while (current.next != null) { current = current.next; } current.next = node; } length++; }
function insertAfter(value, item) { var node = new Node(value); var current = this.find(item); if (current == null) { return console.log(‘找不到元素‘); } node.next = current.next; current.next = node; length++; }
function remove(value) { var previous = this.findPrevious(value); var current = this.find(value); if (previous == null) { return console.log(‘链表中找不到被删除的元素‘); } previous.next = current.next; length--; }
function removeAt(pos) { if (pos > -1 && pos < length) { var current = this.head; var index = 0; if (pos === 0) { this.head = current.next; } else { while (index < pos) { var previous = current; current = current.next; index++; } previous.next = current.next; } length--; } else { return null; } }
function find(value) { var currentNode = this.head; if (currentNode == null) { console.log("这是一个空链表!!!"); return null; } if (currentNode.value === value) { return currentNode; } while (currentNode.next) { currentNode = currentNode.next; if (currentNode.value === value) { return currentNode } } console.log("没有找到该元素!!!"); return null; }
function findPrevious(value) { var current = this.head; if (current == null) { console.log(‘这是一个空链表‘); return null; } while (current.next) { current = current.next; if (current.next.value === value) { return current; } } console.log(‘找不到该元素的前一个元素‘); return null; }
function indexof(value) { var current = this.head; var index = 0; if (current == null) { return null; } else { while (current) { if (current.value === value) { return index; } index++; current = current.next; } } return -1; }
function size(){ return length; }
function getHead(){ return this.head; }
function print() { var current = this.head; while (current != null) { console.log(current.value); current = current.next; } }
var list = new LinkedList(); for (var i = 1; i < 6; i++) { list.push(i); } list.print();
(完)
标签:link color head eth 功能测试 获取 function move rev
原文地址:https://www.cnblogs.com/wangjiachen666/p/9462895.html