-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsequential-search-st.ts
72 lines (64 loc) · 1.54 KB
/
sequential-search-st.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
// 链表结点的定义
export class Node<Key, Value> {
public key: Key
public val: Value
public next: Node<Key, Value>
constructor(key: Key, val: Value, next: Node<Key, Value>) {
this.key = key
this.val = val
this.next = next
}
}
/**
* 顺序查找(基于无序链表)
*/
export default class SequentialSearchST<Key, Value> {
private first: Node<Key, Value> // 链表首结点
private N: number
constructor() {
this.first = null
this.N = 0
}
size(): number {
return this.N
}
keys(): Key[] {
const keys = []
while (this.first !== null) {
keys.push(this.first.key)
this.first = this.first.next
}
return keys
}
// 查找给定的键,返回相关联的值
get(key: Key): Value {
for (let x = this.first; x !== null; x = x.next) {
if (key === x.key) return x.val
}
return null
}
// 查找给定的键,找到则更新其值,否则在表中新建节点
put(key: Key, val: Value) {
for (let x = this.first; x !== null; x = x.next) {
if (key === x.key) {
x.val = val
return
}
}
this.first = new Node<Key, Value>(key, val, this.first)
this.N++
}
delete(key: Key) {
if (key === null) throw new Error('argument to delete() is null')
return this._delete(this.first, key)
}
private _delete(node: Node<Key, Value>, key: Key) {
if (node === null) return null
if (key === node.key) {
this.N--
return node.next
}
node.next = this._delete(node.next, key)
return node
}
}