forked from caochao/cocos_creator_proj_base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linklist.ts
99 lines (93 loc) · 2.02 KB
/
linklist.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
export type LinkListNode<T> = {
key:number;
data:T;
next:LinkListNode<T>;
}
export class LinkList<T>
{
private pool:LinkListNode<T>[];
private _head:LinkListNode<T>;
private _tail:LinkListNode<T>;
constructor()
{
this._head = this._tail = null;
this.pool = [];
}
private spawn_node(key:number, data:T):LinkListNode<T>
{
let node:LinkListNode<T> = this.pool.pop();
if(node)
{
node.key = key;
node.data = data;
node.next = null;
}
else
{
node = {key:key, data:data, next:null};
}
return node;
}
get head():LinkListNode<T>
{
return this._head;
}
append(key:number, data:T):number
{
let node:LinkListNode<T> = this.spawn_node(key, data);
//将node加到linklist末尾
if(this._tail)
{
this._tail.next = node;
this._tail = node;
}
else
{
this._head = this._tail = node;
}
return node.key;
}
remove(key:number):T
{
if(!key)
{
return null;
}
if(!this._head)
{
return null;
}
let prev:LinkListNode<T>;
let curr:LinkListNode<T> = this._head;
while(curr && curr.key != key)
{
prev = curr;
curr = curr.next;
}
//没找到
if(!curr)
{
return null;
}
if(!prev)
{
//curr为头节点(要区分curr是否同时为尾节点)
this._head = curr.next;
if(!curr.next)
{
this._tail = null;
}
}
else
{
//curr非头节点(要区分curr是否为尾节点)
prev.next = curr.next;
if(!curr.next)
{
this._tail = prev;
}
}
this.pool.push(curr);
return curr.data;
}
}