voidinsertSkipList(struct SkipList *list, int val) { int level = randomLevel(); if( level > list -> level) { for(; list -> level < level; list -> level++){ structSkipNode *newNode = createSkipNode(list -> head -> val); newNode -> down = list -> head; list -> head = newNode; } } structSkipNode *update[list -> level]; structSkipNode *cur =list -> head; for(int i = list -> level - 1; i >= 0; i--) { while(cur -> next != NULL && cur -> next -> val < val) { cur = cur -> next; } update[i] = cur; cur = cur -> down; } cur = NULL; for(int i = 0; i < level; i++) { structSkipNode *newNode = createSkipNode(val); newNode -> next = update[i] -> next; update[i] -> next = newNode; if(i > 0) { newNode -> down = cur; } cur = newNode; } }
7,查找节点
1 2 3 4 5 6 7 8 9 10 11 12 13
boolsearchSkipList(struct SkipList *list, int val) { structSkipNode *cur =list -> head; for(int i = list -> level - 1; i >= 0; i--) { while(cur -> next && cur -> next -> val < val) { cur = cur -> next; } if(cur -> next && cur -> next -> val == val) { returntrue; } cur = cur -> down; } returnfalse; }
voiddeleteSkipList(struct SkipList *list, int val) { structSkipNode *cur =list -> head; for(int i = list -> level - 1; i >= 0; i--) { while(cur -> next && cur -> next -> val < val) { cur = cur -> next; } if(cur -> next && cur -> next -> val == val) { structSkipNode *temp = cur -> next; cur -> next = cur -> next -> next; free(temp); } cur = cur -> down; } cur = list -> head; while(cur -> next == NULL && list -> level > 1) { structSkipNode *temp = cur; cur = cur -> down; free(temp); list -> level--; } }
9,打印跳表
1 2 3 4 5 6 7 8 9 10
voidprintSkipList(struct SkipList *list) { structSkipNode *cur =list -> head; for(int i = list -> level - 1; i > 0; i--) { cur = cur -> down; } for(; cur -> next != NULL; cur = cur -> next) { printf("%d ", cur -> next-> val); } printf("\n"); }
10,释放内存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
voidfreeSkipList(struct SkipList *list) { structSkipNode *cur =list -> head; structSkipNode *temp; for(int i = list -> level - 1; i >= 0; i--) { temp = cur -> next; for(;temp; ) { structSkipNode *temp2 = temp; temp = temp -> next; free(temp2); } structSkipNode *temp3 = cur; cur = cur -> down; free(temp3); } free(list); }