MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / insert

Method insert

publication/code/chapter08/rbtree.rs:303–341  ·  view source on GitHub ↗

数据插入

(&mut self, key: K, val: V)

Source from the content-addressed store, hash-verified

301
302 // 数据插入
303 fn insert(&mut self, key: K, val: V) {
304 unsafe {
305 let mut parent = null_mut();
306 let mut node = self.root;
307
308 // 找到待插入节点及其父节点位置
309 while !node.is_null() {
310 parent = node;
311 node = match (*node).key.cmp(&key) {
312 Less => (*node).right,
313 Equal => {
314 (*node).val = val;
315 return;
316 }
317 Greater => (*node).left,
318 }
319 }
320
321 // 数据插入
322 node = Box::into_raw(Box::new(RBNode::new(key, val)));
323
324 // 更新节点关系
325 if !parent.is_null() {
326 if (*node).key < (*parent).key {
327 (*parent).left = node;
328 } else {
329 (*parent).right = node;
330 }
331 } else {
332 self.root = node;
333 }
334
335 // 更新父节点关系
336 (*node).parent = parent;
337
338 // 旋转,更新节点颜色
339 insert_fixup(self, node);
340 }
341 }
342
343 fn delete(&mut self, key: &K) {
344 unsafe {

Callers 7

enqueueMethod · 0.45
basicFunction · 0.45
orderFunction · 0.45
getFunction · 0.45
iterFunction · 0.45
insertFunction · 0.45
deleteFunction · 0.45

Calls 2

insert_fixupFunction · 0.85
cmpMethod · 0.45

Tested by

no test coverage detected