-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkList.js
76 lines (72 loc) · 1.7 KB
/
linkList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//采用链表
//定义链表节点元素,具有存储的值属性,和链属性
function Node ( element ) {
this.element = element;
this.next = null;
}
//定义一个链表构造函数,里面包含一个头结点,和一些相关的方法
function LinkList () {
this.head = new Node( "head" );
this.insert = insert;
this.remove = remove;
this.findpre = findpre;
this.length=length;
this.isEmpty=isEmpty;
this.findNumNode=findNumNode;
this.clear=clear;
}
function findNumNode(d)
{
var currNode=this.head;
for(var i=0;i<=d;i++)
{
if(currNode.next!=null)
{
currNode=currNode.next;
}
}
return currNode.element;
}
//在item 后面插入newElment节点,最后返回this是为了能够实现链式调用
function insert(newElment) {
var newNode = new Node( newElment );
var currNode = this.head;
newNode.next = currNode.next;
currNode.next= newNode;
this.length++;
return this;
}
//找到item 的前一个节点
function findpre ( item ) {
var currNode = this.head;
while ( currNode.next != null && currNode.next.element != item ) {
currNode = currNode.next;
}
return currNode;
}
//遍历链表,删除目标节点
function remove ( element ) {
var pre = this.findpre( element );
if( pre.next != null ) {
pre.next = pre.next.next;
}
this.length--;
return this;
}
//
function isEmpty () {
var currNode = this.head;
if( currNode.next != null ) {
return false;
}
return true;
}
function clear()
{
var currNode=this.head;
if(currNode.next!=null)
{
currNode.next=currNode.next.next;
}
this.length=0;
}