C++ 数据结构学习 ---- 伸展树

本文详细介绍了C++中伸展树(Splay Tree)的数据结构实现,包括插入、删除和搜索等核心操作。通过模板类`Splay<T>`继承自二叉搜索树`BST<T>`,实现了伸展树的伸展算法,确保最近访问的节点被快速访问。插入函数根据节点位置进行嫁接,删除函数处理目标节点的左、右子树,搜索函数则将查找的节点伸展到根。代码还提供了运行示例及结果展示。
摘要由CSDN通过智能技术生成

目录

1. 头文件

2. 相关函数

2.1 插入函数

2.2 删除函数

2.3 搜索函数

2.4  伸展函数

3. 完整代码

4. 代码运行结果截图


1. 头文件

需要引入C++ 数据结构学习 ---- 二叉搜索树_孤城寻欢的博客-CSDN博客的二叉搜索树文件

#include"BST.h"

template <typename T> class Splay : public BST<T> { //由BST派生的Splay树模板类
protected:
	BinNodePosi(T) splay(BinNodePosi(T) v); //将节点v伸展至根
public:
	BinNodePosi(T)& search(const T& e); //查找(重写)
	BinNodePosi(T) insert(const T& e); //插入(重写)
	bool remove(const T& e); //删除(重写)
};
//在节点*p与*lc(可能为空)之间建立父(左)子关系
template <typename NodePosi> inline void attachAsLC(NodePosi lc, NodePosi p) { p->lc = lc; if (lc) lc->parent = p; }
 //在节点*p与*rc(可能为空)之间建立父(右)子关系
template <typename NodePosi> inline void attachAsRC(NodePosi p, NodePosi rc) { p->rc = rc; if (rc) rc->parent = p; }

2. 相关函数

2.1 插入函数

//将关键码e插入伸展树中
template <typename T> BinNodePosi(T) Splay<T>::insert(const T& e) { 
	if (BST<T>::_root==NULL) { this->_size = 1; return this->_root = new BinNode<T>(e); } //原树为空
	BinNodePosi(T) t = search(e); if (e == t->data) return t; //目标节点t若存在,伸展至根
	if (t->data < e) { //在右侧嫁接
		t->parent = this->_root = new BinNode<T>(e, NULL, t, t->rc); //lc == t必非空
		if (t->rc) { t->rc->parent = this->_root; t->rc = NULL; } //rc或为空
	}
	else { //在左侧嫁接
		t->parent = this->_root = new BinNo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值