用优先级队列实现先进先出队列;

代码:

#include "iostream"
#define MAX 0x7fffffff
using namespace std;

int B[20],heap_size=0;

int counter=0;

int parent(int i){
    return i/2;
}

int left(int i){
    return 2*i;
}

int right(int i){
    return 2*i+1;
}

void decrease_Key(int A[],int i,int key){
    int temp;
    A[i]=key;
    while(i>1&&A[parent(i)]>A[i]){
        temp=A[i];
        A[i]=A[parent(i)];
        A[parent(i)]=temp;
        i=parent(i);
    }
}

void insert_MinHeap(int A[],int key){
    heap_size++;
    A[heap_size]=MAX;
    decrease_Key(A,heap_size,key);
}

void minHeapify(int A[],int i){
    int l,r;
    l=left(i);
    r=right(i);
    int smallest;
    if(l<=heap_size&&A[i]>A[l])
        smallest=l;
    else 
        smallest=i;
    if(r<=heap_size&&A[smallest]>A[r])
        smallest=r;
    int temp;
    if(smallest!=i){
        temp=A[i];
        A[i]=A[smallest];
        A[smallest]=temp;
        minHeapify(A,smallest);
    }
}

int extract_MinHeap(int A[]){
    int x=A[1];
    A[1]=A[heap_size];
    heap_size--;
    minHeapify(A,1);
    return x;
}

void enQueue(int A[],int data){
    counter++;
    B[counter]=data;
    insert_MinHeap(A,counter);
}

int deQueue(int A[]){
    int i=extract_MinHeap(A);
    return B[i];
}

int m=0;

int  add(){
    m++;
    return m;
}

void main(){
    int A[20];
    enQueue(A,12);
    enQueue(A,45);
    enQueue(A,34);
    cout<<deQueue(A)<<endl;
    cout<<deQueue(A)<<endl;
    cout<<deQueue(A)<<endl;
    getchar();
    getchar();
}

 

转载于:https://www.cnblogs.com/593213556wuyubao/archive/2012/12/17/2821890.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值