1#include <iostream>2#include <vector>3#include <queue>4 using namespacestd;5Template <typename t>6 classLeftlistnode7 {8 Public:9 T key;Ten intNPL; Oneleftlistnode*Left ; Aleftlistnode*Right ; - -Leftlistnode (t& value, leftlistnode* l = null, leftlistnode* r = null,intn =0): the key (value), left (L), right (R), NPL (n) {} - }; - -Template <typename t> + classleftlistheap{ - Private: +leftlistnode<t>*Mroot; A Public: at leftlistheap () {} -Leftlistheap (vector<t>&items) { -Mroot =buildheap (items); - } -~leftlistheap () { - destory (mroot); in } - voidMerge (leftlistheap<t>*Other ) { to if( This==Other ) + return; -Mroot = _merge (Mroot, other->mroot); the } * voidInsert (t&key) { $Mroot = _merge (Mroot,NewLeftlistnode<t>(key));Panax Notoginseng } - voidRemove () { theleftlistnode<t> old =Mroot; +Mroot = _merge (Mroot->left, mroot->Right ); A delete old; the } + T get_min () { - returnMroot->key; $ } $ - voidDestory (leftlistnode<t>* &mroot) { - if(Mroot = =NULL) the return; - if(Mroot->left! =NULL)WuyiDestory (mroot->Left ); the if(Mroot->right! =NULL) -Destory (mroot->Right ); Wu Delete mroot; - } About $ Private: -leftlistnode<t>* _merge1 (leftlistnode<t>* x, leftlistnode<t>*y) { - if(x = =NULL) - returny; A if(Y = =NULL) + returnx; the if(X->key < y->key) - _merge2 (x, y); $ Else the _merge2 (y, x); the } theleftlistnode<t>* _merge2 (leftlistnode<t>* x, leftlistnode<t>*y) { the if(X->left = =NULL) -X->left =y; in Else{ theX->right = _merge1 (x->Right , y); the if(X->LEFT->NPL < x->right->NPL) { Aboutleftlistnode<t>* temp = x->Left ; theX->left = x->Right ; theX->right =temp; the } +X->NPL = X->RIGHT->NPL +1; - } the returnx;Bayi } the theleftlistnode<t>* _merge (leftlistnode<t>* x, leftlistnode<t>*y) { - if(x = = NULL && y = =NULL) - returnNULL; the Else if(x = = NULL && Y! =NULL) the returny; the Else if(y = = NULL && x! =NULL) the returnx; - Else{ the if(X->key > y->key) { theleftlistnode<t>* tmp =x; thex =y;94y =tmp; the } the if(X->left = =NULL) theX->left =y;98 Else{ AboutX->right = _merge (x->Right , y); - if(X->LEFT->NPL < x->right->NPL) {101leftlistnode<t>* tmp = x->Left ;102X->left = x->Right ;103X->right =tmp;104 } theX->NPL = X->RIGHT->NPL +1;106 }107 }108 returnx;109 } theleftlistnode<t>* Buildheap (vector<t>&items) {111Queue<leftlistnode<t>*>Tmp_queue; the for(inti =0; I < items.size (); ++i)113Tmp_queue.push (NewLeftlistnode<t>(Items[i])); the while(Tmp_queue.size () >1){ theleftlistnode<t>* T1 =Tmp_queue.front (); the Tmp_queue.pop ();117leftlistnode<t>* t2 =Tmp_queue.front ();118 Tmp_queue.pop ();119 Tmp_queue.push (_merge1 (t1, T2)); - }121 returnTmp_queue.front ();122 }123 124 }; the 126 intMain () {127 inta[]= { -, +, -, -, $, -, A, -}; -vector<int> lt (A, A +7);129leftlistheap<int>YJ (LT); thecout << yj.get_min () <<Endl;131 return 0; the}
Left-leaning heap C + + implementation