数据结构-左式堆

左式堆:同二叉堆一样具有结构性和堆序性。惟一的区别是:左式堆不是理想平衡的,而实际上是趋于不平衡的。

零路径长(NPL(x)):从节点x到一个没有两个儿子节点的最短路径长。

左式堆要求对于堆中的每一个节点x,左儿子的零路径长至少与右儿子的零路径长一样大。

左式堆的结构声明:

struct treeNode;
typedef struct treeNode *priorityQueue;


struct treeNode
{
	int element;
	priorityQueue left;
	priorityQueue right;
	int npl;
};


priorityQueue initialize(priorityQueue h);
void swapChildren(priorityQueue h);
priorityQueue merge(priorityQueue h1, priorityQueue h2);
static priorityQueue merge1(priorityQueue h1, priorityQueue h2);
priorityQueue insert1(int x, priorityQueue h);
int isEmpty(priorityQueue h);
priorityQueue deleteMin1(priorityQueue h);
void printQueue(priorityQueue h);

合并左式堆的驱动例程:
priorityQueue merge(priorityQueue h1, priorityQueue h2)
{
	if (h1 == NULL)
		return h2;
	if (h2 == NULL)
		return h1;
	if (h1->element < h2->element)
		return merge1(h1, h2);
	else
		return merge1(h2, h1);
}

合并左式堆的实际例程:

void swapChildren(priorityQueue h)
{
	priorityQueue r = h->left;
	h->left = h->right;
	h->right = r;
}


static priorityQueue merge1(priorityQueue h1, priorityQueue h2)
{
	if (h1->left == NULL)
		h1->left = h2;
	else
	{
		h1->right = merge(h1->right, h2);
		if (h1->left->npl < h1->right->npl)
			swapChildren(h1);
		h1->npl = h1->right->npl + 1;
	}
	return h1;
}

插入例程:

priorityQueue insert1(int x, priorityQueue h)
{
	priorityQueue singleNode;
	singleNode = (struct treeNode *)malloc(sizeof(struct treeNode));
	if (singleNode == NULL)
		cout << "Out of space!" << endl;
	else
	{
		singleNode->element = x;
		singleNode->npl = 0;
		singleNode->right = singleNode->left = NULL;
		h = merge(singleNode, h);
	}
	return h;
}

DeleteMin例程:

int isEmpty(priorityQueue h)
{
	if (h == NULL)
		return 1;
	else
		return 0;
}


priorityQueue deleteMin1(priorityQueue h)
{
	priorityQueue leftHeap, rightHeap;
	if (isEmpty(h))
	{
		cout << "Queue is null!" << endl;
		return h;
	}
	leftHeap = h->left;
	rightHeap = h->right;
	free(h);
	return merge(leftHeap, rightHeap);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值