javascript 链表

 1     function Node(element) {
 2             this.element = element
 3             this.next = null
 4         }
 5         
 6         function Link() {
 7             this.head = new Node('head')
 8             this.find = find
 9             this.insert = insert
10             this.findPre = findPre
11             this.remove = remove
12             this.display = display
13         }
14 
15         function find(element) {
16             var currentNode = this.head
17             while( currentNode.element != element) {
18                 currentNode = currentNode.next
19             }
20             return currentNode
21         }
22 
23         function insert(newElement, element) {
24             var currentNode = this.find(element)
25             var newNode = new Node(newElement)
26             newNode.next = currentNode.next
27             currentNode.next = newNode
28         }
29 
30         function display() {
31             var currentNode = this.head
32             while(currentNode.next !== null) {
33                 document.write(currentNode.next.element + ' ')
34                 currentNode = currentNode.next
35             }
36         }
37 
38         function findPre(element) {
39             var currentNode = this.head
40             while(currentNode.next.element !== element) {
41                 currentNode = currentNode.next
42             }
43             return currentNode
44         }
45 
46         function remove(element) {
47             var preNode = this.findPre(element)
48             var currentNode = this.find(element)
49             preNode.next = currentNode.next
50             currentNode.next = null
51         }
52 
53         var colors = new Link()
54         colors.insert('red', 'head')
55         colors.insert('blue', 'red')
56         colors.insert('yellow', 'blue')
57         colors.insert('green', 'blue')
58         colors.display() // red blue green yellow
59         colors.remove('blue')
60         colors.display() // red green yellow 

 

posted on 2019-03-08 15:52  时光游弋  阅读(118)  评论(0编辑  收藏  举报