Splay模板
#include <iostream>
using namespace std;
class SplayTree
{
public:
struct Node
{
int key;
Node *pFather,*pLeft,*pRight;
} *pRoot;
SplayTree()
{
pRoot=NULL;
}
void LeftRotate(Node *px)
{
Node *py=px->pFather;
py->pRight=px->pLeft;
if(px->pLeft) px->pLeft->pFather=py;
px->pFather=py->pFather;
if(py->pFather)
{
if(py==py->pFather->pLeft)
py->pFather->pLeft=px;
else
py->pFather->pRight=px;
}
px->pLeft=py;
py->pFather=px;
}
void RightRotate(Node *px)
{
Node *py=px->pFather;
py->pLeft=px->pRight;
if(px->pRight)
px->pRight->pFather=py;
px->pFather=py->pFather;
if(py->pFather)
{
if(py==py->pFather->pLeft)
py->pFather->pLeft=px;
else
py->pFather->pRight=py;
}
px->pRight=py;
py->pFather=px;
}
void Splay(Node *px)
{
while(px->pFather)
{
Node *py=px->pFather;
if(!py->pFather)
{
if(px==py->pLeft) RightRotate(px);
else LeftRotate(px);
break;
}
else if(px==py->pLeft)
{
if(py==py->pFather->pLeft)
{
RightRotate(py);
RightRotate(px);
}
else
{
RightRotate(px);
RightRotate(px);
}
}
else if(px==py->pRight)
{
if(py==py->pFather->pRight)
{
LeftRotate(py);
LeftRotate(px);
}
else
{
LeftRotate(px);
LeftRotate(px);
}
}
}
}
Node *Insert(Node *pFather,Node *&px,int key)
{
if(px==NULL)
{
px=new Node;
px->key=key;
px->pLeft=NULL;
px->pRight=NULL;
px->pFather=pFather;
}
else if(px->key>key)
{
return Insert(px,px->pLeft,key);
}
else
{
return Insert(px,px->pRight,key);
}
}
void Insert(int key)
{
Node *px=Insert(NULL,pRoot,key);
Splay(px);
}
Node *Find(Node *px,int key)
{
if(px==NULL)
return NULL;
else if(px->key>key)
return Find(px->pLeft,key);
else if(px->key<key)
return Find(px->pRight,key);
else
return px;
}
bool Find(int key)
{
Node *px=Find(pRoot,key);
if(px)
{
Splay(px);
return true;
}
else
return false;
}
};
int main()
{
SplayTree sptree;
sptree.Insert(1);
cout<<sptree.Find(1)<<endl;
}