伸展树(3)
作者:
Drifter
,
2020-09-27 20:44:40
,
所有人可见
,
阅读 541
//自顶向下伸展树的插入
SplayTree Insert(ElementType Item, SplayTree T)
{
static Position NewNode = NULL;
if(NewNode == NULL)
{
NewNode = malloc(sizeof(struct SplayNode);
if(NewNode == NULL)
FatalError("Out of space!!!");
}
NewNode->Element = Item;
if(T == NullNode)
{
NewNode->Left = NewNode->Right = NullNode;
T = NewNode;
}
else
{
T = Splay(Item, T);
if(Item < T->Element)
{
NewNode->Left = T->Left;
NewNode->Right = T;
T->Left = NullNode;
T = NewNode;
}
else if(Item > T->Element)
{
NewNode->Right = T->Right;
NewNode->Left = T;
T->Right = NullNode;
T = NewNode;
}
else return T;
}
NewNode = NULL; /*So next insert will call malloc;*/
return T;
}
//自顶向下的删除过程
SplayTree Remove(ElementType Item, SplayTree T)
{
Position NewTree;
if(T != NullNode)
{
T = Splay(Item, T);
if(Item == T->Element)
{
if(T->Left == NullNode)
NewTree = T->Right;
else
{
NewTree = T->Left;
NewTree = Splay(Item, NewTree);
NewTree->Right = T->Right;
}
free(T);
T = NewTree;
}
}
return T;
}