#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;
#define Nil '\0'
const int MaxKeyLen = 16;
typedef struct
{
char ch[MaxKeyLen + 1];
int len;
}KeyType;
typedef struct
{
KeyType key;
//Other others;
int id;
}Record;
typedef enum {LEAF,BRACH} NodeKind;
typedef struct DLTNode
{
char symbol;//关键码一个字符
struct DLTNode* next;//右兄弟
//NodeKind node;
union
{
Record* infoptr;//叶子结点记录指针
struct DLTNode* first;//左孩子
};
}DLTNode;
typedef struct
{
DLTNode* root;
int cursize;
}DLTree;
DLTNode* BuyNode()
{
DLTNode* s = (DLTNode*)calloc(1, sizeof(DLTNode));
if (nullptr == s) exit(EXIT_FAILURE);
return s;
}
void FreeNode(DLTNode* ptr)
{
free(ptr);
}
void InitDLTree(DLTree* ptree)
{
assert(ptree != nullptr);
ptree->root = BuyNode();
ptree->root->symbol = Nil;
ptree->cursize = 0;
}
Record* SearchDLTree(DLTree* ptree, KeyType kx)
{
Record* recptr = nullptr;
if (ptree == nullptr || ptree->root == nullptr) return recptr;
DLTNode* p = ptree->root->first;
int i = 0;
while (p != nullptr && i < kx.len)
{
while (p != nullptr && p->symbol != kx.ch[i])
{
p = p->next;
}
if (p != nullptr && i < kx.len)
{
p = p->first;
}
++i;
}
if (p != nullptr && p -> symbol == Nil)
{
recptr = p->infoptr;
}
return recptr;
}
void Insert_Item(DLTree* ptree, Record* ptr)
{
DLTNode* pa = ptree->root;
DLTNode* p = ptree->root->first;
DLTNode* s = nullptr;
int i = 0;
while (p != nullptr && i < ptr->key.len)
{
while (p->next != nullptr && ptr->key.ch[i] > p->symbol)
{
pa = p;
p = p->next;
}
if (p->symbol != ptr->key.ch[i]) break;
if (p->first != nullptr && p->symbol == ptr->key.ch[i])
{
pa = p;
p = p->first;
}
++i;
}
s = BuyNode();
s->symbol = ptr->key.ch[i];
if (p == nullptr)
{
pa->first = s;
}
else if (ptr->key.ch[i] < p->symbol)
{
s->next = p;
pa->first = s;
}
else
{
pa = p;
p = p->next;
s->next = p;
pa->next = s;
}
pa = s;
for (i += 1; i < ptr->key.len; ++i)
{
s = BuyNode();
s->symbol = ptr->key.ch[i];
pa->first = s;
pa = s;
}
if (i <= ptr->key.len)
{
s = BuyNode();
}
s->symbol = Nil;
pa->first = s;
s->infoptr = ptr;
ptree->cursize += 1;
}
int main()
{
Record record[] = { {{"CAI"},12},{{"CAO"},23},{{"LI"},34},{{"LAN"},45},
{{"CHA"},56},{{"CHANG"},67},{{"WEN"},78},{{"CHAO"},89},
{{"YUN"},90},{{"YANG"},100},{{"LONG"},110},{{"WANG"},123},
{{"ZHAO"},234},{{"LIU"},345},{{"WU"},456},{{"CHEN"},567} };
int n = sizeof(record) / sizeof(record[0]);
DLTree tree;
InitDLTree(&tree);
for (int i = 0; i < n; ++i)
{
record[i].key.len = strlen(record[i].key.ch);
Record* p = SearchDLTree(&tree, record[i].key);
if (nullptr == p)
{
Insert_Item(&tree, &record[i]);
}
}
return 0;
}