From 88b6d1bddd34739ce41bb4b3a01b2c71819eb6f6 Mon Sep 17 00:00:00 2001 From: lichao Date: Thu, 9 May 2019 16:38:59 +0800 Subject: [PATCH] =?UTF-8?q?feature:=E5=A2=9E=E5=8A=A0append=E5=87=BD?= =?UTF-8?q?=E6=95=B0=EF=BC=8C=E6=89=93=E5=8D=B0=E6=9F=A5=E6=89=BE=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E5=BF=BD=E7=95=A5head=E6=8C=87=E5=90=91=E7=9A=84?= =?UTF-8?q?=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/06_linkedlist/SinglyLinkedList.js | 32 ++++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/javascript/06_linkedlist/SinglyLinkedList.js b/javascript/06_linkedlist/SinglyLinkedList.js index 17717b3..bc69148 100644 --- a/javascript/06_linkedlist/SinglyLinkedList.js +++ b/javascript/06_linkedlist/SinglyLinkedList.js @@ -15,7 +15,7 @@ class LinkedList { } // 根据value查找节点 findByValue (item) { - let currentNode = this.head + let currentNode = this.head.next while (currentNode !== null && currentNode.element !== item) { currentNode = currentNode.next } @@ -23,9 +23,9 @@ class LinkedList { return currentNode === null ? -1 : currentNode } - // 根据index查找节点 + // 根据index查找节点,下标从0开始 findByIndex (index) { - let currentNode = this.head + let currentNode = this.head.next let pos = 0 while (currentNode !== null && pos !== index) { currentNode = currentNode.next @@ -33,7 +33,17 @@ class LinkedList { } console.log(currentNode) return currentNode === null ? -1 : currentNode - } + } + + // 向链表末尾追加节点 + append(newElement) { + const newNode = new Node(newElement) + let currentNode = this.head + while(currentNode.next) { + currentNode = currentNode.next + } + currentNode.next = newNode + } // 指定元素向后插入 insert (newElement, element) { @@ -71,7 +81,7 @@ class LinkedList { // 遍历显示所有节点 display () { - let currentNode = this.head + let currentNode = this.head.next while (currentNode !== null) { console.log(currentNode.element) currentNode = currentNode.next @@ -80,10 +90,14 @@ class LinkedList { } // Test const LList = new LinkedList() -LList.insert('chen', 'head') -LList.insert('curry', 'chen') -LList.insert('sang', 'head') -LList.insert('zhao', 'head') +LList.append('chen') +LList.append('curry') +LList.append('sang') +LList.append('zhao') // chen -> curry -> sang -> zhao +console.log('-------------insert item------------') +LList.insert('qian', 'chen') // 首元素后插入 +LList.insert('zhou', 'zhao') // 尾元素后插入 +LList.display() // chen -> qian -> curry -> sang -> zhao -> zhou console.log('-------------remove item------------') LList.remove('curry') LList.display()