JavaScript数据结构-8.双向链表
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>双向链表</title> 6 </head> 7 <body> 8 <script> 9 function Node(ele){ 10 this.ele = ele; 11 this.prev = this.next = null; 12 } 13 14 function linkList(){ 15 this.head = new Node("head"); 16 this.find = find; 17 this.insert = insert; 18 this.findLast = findLast; 19 this.display = display; 20 this.disReverse = disReverse; 21 this.remove = remove; 22 23 } 24 function find(item){ 25 var currNode = this.head; 26 while (currNode.ele != item){ 27 currNode = currNode.next; 28 } 29 return currNode; 30 } 31 function insert(newEle,item){ 32 var newNode = new Node(newEle); 33 var current = this.find(item); 34 newNode.next = current.next; 35 newNode.prev = current; 36 current.next = newNode; 37 } 38 39 function display(){ 40 var currNode = this.head; 41 while(currNode.next != null){ 42 console.log(currNode.next.ele); 43 currNode = currNode.next; 44 } 45 return currNode; 46 } 47 48 function findLast(){ 49 var currNode = this.head; 50 while(currNode.next != null){ 51 currNode = currNode.next; 52 } 53 return currNode; 54 } 55 56 function remove(item){ 57 var currNode = this.find(item); 58 if(currNode.next != null){ 59 currNode.prev.next =currNode.next; 60 currNode.next.prev = currNode.prev; 61 currNode.next = null; 62 currNode.prev = null; 63 } 64 } 65 66 function disReverse(){ 67 var currNode = this.findLast(); 68 while(currNode.prev != null ){ 69 console.log(currNode.ele); 70 currNode = currNode.prev; 71 } 72 } 73 74 75 //测试 76 var obj = new linkList(); 77 obj.insert("zhangsan","head"); 78 obj.insert("lisi","zhangsan"); 79 obj.insert("zhaowu","lisi"); 80 obj.insert("wangliu","zhaowu"); 81 console.log(obj.findLast()); 82 obj.display(); 83 obj.disReverse(); 84 obj.remove("lisi"); 85 obj.display(); 86 </script> 87 </body> 88 </html>