学习JavaScript 数据结构与算法【Loiane Groner著】【第一版】之完善
- 双向链【p59】
当position大于length/2时,应从尾部进行迭代,否则双向便失去意义
// insert部分
// 选择的位置大于length/2时,从尾部进行迭代
if(p > Math.floor(length/2)){
index = length;
current = tail;
while(--index > p){
current = current.prev;
}
node.prev = current.prev;
current.prev.next = node;
node.next = current;
current.prev = node;
}else{
while (index++ < p) {
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
current.prev = node;
node.prev = previous;
}
// removeAt部分
// 选择的位置大于length/2时,从尾部进行迭代
if(p > Math.floor(length/2)){
index = length;
current = tail;
while(--index > p){
current = current.prev;
}
current.prev.next = current.next.next;
current.next.prev = current.prev;
}else{
while (index++ < p) {
previous = current;
current = current.next;
}
previous.next = current.next;
current.next.prev = previous;
}
// getIndex部分
// 选择的位置大于length/2时,从尾部进行迭代
if(p > Math.floor(length/2)){
index = length;
current = tail;
while(--index > p){
current = current.prev;
}
}else{
while (index++ < p) {
current = current.next;
}
}
- 散列表【p85】
put方法需要判断追加的元素的key是否已存在,否则使用remove方法时并不能将table[position]中对应的key完全删除
this.put = function (key, val) {
var position = loseHashCode(key);
if (table[position] == undefined) {
table[position] = new LinkedList();
}
var current = table[position].getHead();
var flag = 0;
while (current) {
if (current.e.key == key) { // 已存在该key,则更新该key对应的value
current.e.val = val;
flag = 1;
}
current = current.next;
}
// 不存在该key则追加元素
if (flag == 0) {
table[position].append(new ValuePair(key, val));
}
};
使用书中的put方法,则若有如下运行情况时,remove的删除将存在问题
var h = new HashTable();
h.put('abc', '123');
h.put('abc', '1234');
h.print(); // 35: [abc-123][abc-1234]
h.remove('abc');
h.print(); // 35: [abc-1234] 删除不干净, 仍有abc键
但在看了p115图的描述中,似乎字典的要求的就是不需要更新值,只需要不断追加即可,否则如上修改后,图将无法实现。。。