跳表根据逐层元素减半的方式,能够对有序链表进行快速的插入,查找,删除等操作。
skip_list.h声明
#define MAX_LEVEL 8
typedef struct Node_s
{
int value;
struct Node_s *next[1];
}Node;
typedef struct SkipList_s
{
int level;
Node *head;
}SkipList;
Node *CreateNode(int level, int value);
SkipList *Init();
int Random();
void Insert(SkipList *list, int value);
void Delete(SkipList *list, int value);
void Show(SkipList *list);
skip_list.c内部实现
#include <stdio.h>
#include <stdlib.h>
#include "slip_list.h"
Node *CreateNode(int level, int value)
{
Node *node = (Node *)malloc(sizeof(Node) + (level - 1) * sizeof(Node *));
node->value = value;
return node;
}
SkipList *Init()
{
int i;
SkipList *list = (SkipList *)malloc(sizeof(SkipList));
list->level = 0;
list->head = CreateNode(MAX_LEVEL, 0);
for (i = 0; i < MAX_LEVEL; i++) {
list->head->next[i] = NULL;
}
return list;
}
int Random()
{
int k = 1;
while (rand() % 2) {
k++;
}
return k > MAX_LEVEL ? MAX_LEVEL : k;
}
void Insert(SkipList *list, int value)
{
int i, k;
Node *update[MAX_LEVEL];
Node *node;
Node *p, *q = NULL;
p = list->head;
k = list->level;
for (i = k - 1; i >= 0; i--) {
while ((q = p->next[i]) && (q->value <= value)) {
if (q->value == value) {
printf("error:insert error %d\n", value);
return;
}
p = q;
}
update[i] = p;
}
k = Random();
if (k > list->level) {
for (i = list->level; i < k; i++) {
update[i] = list->head;
}
list->level = k;
}
node = CreateNode(k, value);
printf("k: %d level: %d\n", k, list->level);
for (i = 0; i < k; ++i) {
node->next[i] = update[i]->next[i];
update[i]->next[i] = node;
}
}
void Delete(SkipList *list, int value)
{
int i, k;
Node *update[MAX_LEVEL];
Node *p, *q = NULL;
p = list->head;
k = list->level;
for (i = k - 1; i >= 0; i--) {
while ((q = p->next[i]) && q->value < value) {
p = q;
}
update[i] = p;
}
if (q && (q->value == value)) {
for (i = 0; i < k; i++) {
if (update[i]->next[i] == q) {
update[i]->next[i] = q->next[i];
}
}
free(q);
for (i = list->level - 1; i >= 0; i--) {
if (list->head->next[i] == NULL) {
list->level--;
}
}
}
}
void Show(SkipList *list)
{
int i;
Node *p, *q = NULL;
for (i = list->level - 1; i >= 0; i--) {
printf("\n======== levle %d ========\n", i);
p = list->head;
while (q = p->next[i]) {
printf("%d -> ", q->value);
p = q;
}
printf("\n");
}
printf("\n");
}
主函数测试代码:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include "slip_list.h"
typedef unsigned int uint32;
uint32 get_time()
{
uint32 current_time = 0;
current_time = GetTickCount();
return current_time;
}
int main()
{
int i;
int ar[] = {5, 7, 6, 4, 3, 9, 0, 1, 8, 2, 2};
uint32 start_time, end_time;
SkipList *list;
list = Init();
start_time = get_time();
for (i = 0; i < 40000; i++) {
Insert(list, rand());
}
end_time = get_time();
printf("Time consumed %d\n", end_time - start_time);
Show(list);
Show(list);
Delete(list, 8);
Show(list);
_asm int 3
}