getNodeByRank is a method of the SkipList type that is used to retrieve a node based on its rank within the list. The method takes as argument an integer rank and returns a pointer to the SkipListNode at the specified rank, or nil if there is no such node. First, the method initializes a variable t
(rank int)
| 443 | // If during the traversal the cumulative span equals the target rank, the method returns the getNodeByRank node. |
| 444 | // If the end of the SkipList is reached, or the target rank isn't found on any level, the method returns nil. |
| 445 | func (sl *SkipList) getNodeByRank(rank int) *SkipListNode { |
| 446 | // This variable is used to keep track of the number of nodes we have |
| 447 | // traversed while going through the levels of the SkipList. |
| 448 | var traversed int |
| 449 | |
| 450 | // Define a SkipListNode pointer h, initialized with sl.head |
| 451 | // At the start, this pointer is set to head node of the SkipList. |
| 452 | h := sl.head |
| 453 | |
| 454 | // The outer loop decrements levels from highest level to lowest. |
| 455 | for i := sl.level - 1; i >= 0; i-- { |
| 456 | |
| 457 | // The inner loop traverses the nodes at current level while the next node isn't null and we haven't traversed beyond the 'rank'. |
| 458 | // The traversed variable is also updated to include the span of the current level. |
| 459 | for h.level[i].next != nil && (traversed+h.level[i].span) <= rank { |
| 460 | traversed += h.level[i].span |
| 461 | h = h.level[i].next |
| 462 | } |
| 463 | |
| 464 | // If traversed equals 'rank', it means we've found the node at the rank we are looking for. |
| 465 | // So, return the node. |
| 466 | if traversed == rank { |
| 467 | return h |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | // If the node at 'rank' wasn't found in the SkipList, return nil. |
| 472 | return nil |
| 473 | } |
| 474 | |
| 475 | // ZAdd adds a value with its given score and member to a sorted set (ZSet), associated with |
| 476 | // the provided key. It is a method on the ZSetStructure type. |
no outgoing calls