The source code is as follows:
#include <stdlib.h> #include <stdio.h>//#define Key int#define hl h->l#define hr h->r#define HLR h-> L->r#define hll h->l->l#define HRR h->r->r#define hrl h->r->ltypedef int key;struct Item{Key Key; char c;}; typedef struct STNODE* link;struct stnode{item Item; link l,r; int N;}; Static link head, Z; static struct Item nullitem; Key key (item item) {return item.key;} Create a node link NEW (item item, link L,link r, int N) {link x = (link) malloc (sizeof *x); X->item = Item;x->l = L;x->r = R;x->n = N;if (head==z) head=x; This sentence can not be less!!! return x;} initialize void Stinit () {head = (z = NEW (nullitem,0,0,0));} Right rotation clockwise rotation link ROTR (link h) {link x = h->l; h->l = x->r; x->r=h;}//Left rotation counterclockwise turn link rotl (link h) {link x = H-&G T;r; H->r = x->l; X->l=h;} Root Insert Program link insertt (link h, item item) {//key v = key (item), T = key (H->item), char v = item.c, t = h->item.c;if (h==z Return NEW (item,z,z,1), if (v<t) {h->l = Insertt (h->l,item); h = ROTR (h); }else {h->r = Insertt (h->r,item); h = rotl (h);} (h->n) ++;return h;} Randomize the Insert Program link INSERTR (link h, item item) {//key v = key (item), T = key (H->item), char v = item.c, t = h->item.c;if (h= =Z) return NEW (item,z,z,1), if (rand () < Rand_max/(h->n+1)) return Insertr (H,item); The probability that the new node appears on the root of the tree is 1/(n+1) if (v<t) {h->l = INSERTR (h->l,item); h = ROTR (h);} else {h->r = INSERTR (h->r,item); h = rotl (h);} (h->n) ++;return h;} Stretch Insert link splay (link h, item item) {Char v = item.c, t = h->item.c;if (h==z) return NEW (item,z,z,1); if (v<t) {if (hl==z) Return NEW (item,z,h,h->n+1), if (V<HL->ITEM.C) {hll=splay (hll,item); h = ROTR (h);} ELSE{HLR = splay (Hlr,item); hl = Rotl (HL);} return ROTR (h);} else {if (hr==z) return NEW (item,h,z,h->n+1), if (V>HR->ITEM.C) {hrr=splay (hrr,item); h = rotl (h);} Else{hrl = splay (hrl,item); hr = ROTR (hr);} return Rotl (h);}} BST Insert main program void Stinsert (item item) {//The newly inserted node will be treated as root node head = splay (Head,item);} void Sortr (link h) {if (h==z) return;printf ("%C ", H->ITEM.C); Sortr (h->l); Sortr (h->r);} Binary search tree sort void stsort (link h) {sortr (h);} void Test () {struct Item item1 = {322, ' a '};struct item item2 = {23°c, ' s '};struct item item3 = {2, ' E '};struct item item4 = {33 2, ' R '};struct Item ITEM5 = {332, ' C '};struct item ITEM6 = {332, ' h '};struct item Item7 = {, ' I '}; Stinit (); Stinsert (ITEM1); Stinsert (ITEM2); Stinsert (ITEM3); Stinsert (ITEM4); Stinsert (ITEM5); Stinsert (ITEM6); Stinsert (ITEM7); Stsort (head);} Main () {test ();}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
randomized insertion and extension insertion of binary search trees (split method)