Treap堆的插入,删除操作

#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <time.h>
#include <iostream>
using namespace std;
typedef struct node
{
  node* left;
  node* right;
  int priority;
  int key;
}*Node;
typedef struct treap
{
  Node root;
}*Treap;
void rotate_left(Node node)
{
  Node x = node->right;
  node->right = x->left;
  x->left = node;
  node = x;
}
void rotate_right(Node node)
{
  Node x = node->left;
  node->left = x->right;
  x->right = node;
  node = x;
}
void insert(Node root, int key, int priority)
{
  if (root == NULL)
  {
    root = (Node)malloc(sizeof(Node));
    root->left = NULL;
    root->right = NULL;
    root->priority = priority;
    root->key = key;
  }
  else if (key < root->key)
  {
    insert(&(root->left), key, priority);
    if (root->left->priority < root->priority)
      rotate_right(root);
  }
  else
  {
    insert(&(root->right), key, priority);
    if (root->right->priority < root->priority)
      rotate_left(root);
  }
}
void deletenode(Node root, int key)
{
  if (root != NULL)
  {
    if (key < root->key)
      deletenode(&(root->left), key);
    else if (key > root->key)
      deletenode(&(root->right), key);
    else
    {
      if (root->left == NULL)
        root = root->right;
      else if (root->right == NULL)
        root = root->left;
      else
      {
        if (root->left->priority < root->right->priority)
        {
          rotate_right(root);
          deletenode(&(root->right), key);
        }
        else
        {
          rotate_left(root);
          deletenode(&(root->left), key);
        }
      }
    }
  }
}
void output(Node tree, int key, int x)
{
    if(tree != NULL)
    {
        if(x==0)    
			cout << setw(2) << tree->key <<" is root" << "  优先级为:"<<tree->priority<<endl;
        else                
			cout << setw(2) << tree->key <<" is " << setw(2) << key << "'s "  << setw(12) << (x==1?"right child" : "left child") << "  优先级为:"<<tree->priority<<endl;

        output(tree->left, tree->key, -1);
        output(tree->right,tree->key,  1);
    }
}
void output(Node mRoot)
{
    if (mRoot != NULL)
		output(mRoot, mRoot->key, 0);
}

int main()
{
  Treap treap = (Treap)malloc(sizeof(Treap));
  treap->root = NULL;
  int i = 0;
  cout<<"请输入要插入的节点的数目:"<<endl;
  int n,a[20];
  cin>>n;
  srand(time(0));
  cout<<"请输入要插入节点的key值:"<<endl;
  for (i = 0; i < n; i++)
  {
	cin>>a[i];
    insert(&(treap->root), a[i], rand());
  }
  output(treap->root);
    cout<<"请输入要删除节点的key值:"<<endl;
	cin>>n;
    deletenode(&(treap->root), n);
	output(treap->root);
  system("pause");
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值