设计一个基于对象的链表 咱们设计的链表包含两个类。前端
Node 类用来表示节点函数
LinkedList 类提供了插入节点、删除节点、显示列表元素的方法,以及其余一些辅助方法。this
Node 类包含两个属性:element 用来保存节点上的数据,next 用来保存指向下一个节点的
连接。咱们使用一个构造函数来建立节点,该构造函数设置了这两个属性的值:spa
function Node(element) { this.element = element; this.next = null; }
LList 类提供了对链表进行操做的方法。该类的功能包括插入删除节点、在列表中查找给 定的值。该类也有一个构造函数,链表只有一个属性,那就是使用一个 Node 对象来保存该 链表的头节点。
该类的构造函数以下所示:设计
function LList() { this.head = new Node("head"); this.find = find; this.insert = insert; this.remove = remove; this.display = display; }
function Node(element) { this.element = element; this.next = null; } function LList() { this.head = new Node("head"); this.find = find; this.insert = insert; this.display = display; this.findPrevious = findPrevious; this.remove = remove; } function remove(item) { var prevNode = this.findPrevious(item); if (!(prevNode.next == null)) { prevNode.next = prevNode.next.next; } } function findPrevious(item) { var currNode = this.head; while (!(currNode.next == null) && (currNode.next.element != item)) { currNode = currNode.next; } return currNode; } function display() { var currNode = this.head; while (!(currNode.next == null)) { print(currNode.next.element); currNode = currNode.next; } } function find(item) { var currNode = this.head; while (currNode.element != item) { currNode = currNode.next; } return currNode; } function insert(newElement, item) { var newNode = new Node(newElement); var current = this.find(item); newNode.next = current.next; current.next = newNode; }
固然,学好前端,你还须要关注一个公众号!——每日前端
各位兄弟姐妹,共勉!code