skiplist.c 1.7 KB
Newer Older
H
more  
hzcheng 已提交
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
#include <stdlib.h>

#include "skiplist.h"

#define IS_VALID_SKIPLIST_DUPLICATE_KEY_STRATEGY(strategy) \
  (((strategy) >= SKIPLIST_ALLOW_DUPLICATE_KEY) && ((strategy) <= SKIPLIST_DISCARD_DUPLICATE_KEY))

SSkipListNode *tdCreateSkiplistNode(int32_t nlevels) {
  SSkipListNode *pNode = (SSkipListNode *)malloc(sizeof(SSkipListNode));
  if (pNode == NULL) return NULL;

  pNode->nexts = (struct _skiplist_node **)cmalloc(nlevels, sizeof(struct _skiplist_node *));
  if (pNode->nexts == NULL) {
    free(pNode);
    return NULL;
  }

  pNode->prevs = (struct _skiplist_node **)cmalloc(nlevels, sizeof(struct _skiplist_node *));
  if (pNode->nexts == NULL) {
    free(pNode->nexts);
    free(pNode);
    return NULL;
  }

  return pNode;
}

int32_t tdFreeSkiplistNode(SSkipListNode *pNode) {
    if (pNode == NULL) return 0;
    // TODO: free key and free value

    // Free the skip list
    free(pNode->nexts);
    free(pNode->prevs);
    free(pNode);
    return 0;
}

SSkipList *tdCreateSkiplist(int16_t nMaxLevels, SKIPLIST_DUPLICATE_KEY_STATEGY strategy) {
  // Check parameters
  if (!IS_VALID_SKIPLIST_DUPLICATE_KEY_STRATEGY(strategy)) return NULL;

  SSkipList *pSkipList = (SSkipList *)malloc(sizeof(SSkipList));
  if (pSkipList == NULL) {
    return NULL;
  }

  pSkipList->strategy = strategy;
  pSkipList->nMaxLevels = nMaxLevels;

  pSkipList->head = tdCreateSkiplistNode(nMaxLevels);
  if (pSkipList->head == NULL) {
    free(pSkipList);
    return NULL;
  }

  return pSkipList;
}

int32_t tdFreeSkipList(SSkipList *pSkipList) {
  if (pSkipList == NULL) return 0;

  SSkipListNode *pNode = pSkipList->head->nexts[0];
  while (pNode) {
      SSkipListNode *pTemp = pNode->nexts[0];
      tdFreeSkiplistNode(pNode);
      pNode = pTemp;
  }

  free(pSkipList);

  return 0;
}