splaytree.c 19 KB
Newer Older
1 2 3
/*****************************************************************************
 * splaytree.c:
 *****************************************************************************
4
 * Copyright (C) 2004 the VideoLAN team
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * $Id$
 *
 * Authors: Cyril Deguet <asmax@videolan.org>
 *          code from projectM http://xmms-projectm.sourceforge.net
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Antoine Cellerier's avatar
Antoine Cellerier committed
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27 28 29
 *****************************************************************************/



/*
                An implementation of top-down splaying
                    D. Sleator <sleator@cs.cmu.edu>
30
    	                     March 1992
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

  "Splay trees", or "self-adjusting search trees" are a simple and
  efficient data structure for storing an ordered set.  The data
  structure consists of a binary tree, without parent pointers, and no
  additional fields.  It allows searching, insertion, deletion,
  deletemin, deletemax, splitting, joining, and many other operations,
  all with amortized logarithmic performance.  Since the trees adapt to
  the sequence of requests, their performance on real access patterns is
  typically even better.  Splay trees are described in a number of texts
  and papers [1,2,3,4,5].

  The code here is adapted from simple top-down splay, at the bottom of
  page 669 of [3].  It can be obtained via anonymous ftp from
  spade.pc.cs.cmu.edu in directory /usr/sleator/public.

  The chief modification here is that the splay operation works even if the
  item being splayed is not in the tree, and even if the tree root of the
  tree is NULL.  So the line:

                              t = splay(i, t);

  causes it to search for item with key i in the tree rooted at t.  If it's
  there, it is splayed to the root.  If it isn't there, then the node put
  at the root is the last one before NULL that would have been reached in a
  normal binary search for i.  (It's a neighbor of i in the tree.)  This
  allows many other operations to be easily implemented, as shown below.

  [1] "Fundamentals of data structures in C", Horowitz, Sahni,
       and Anderson-Freed, Computer Science Press, pp 542-547.

  [2] "Data Structures and Their Algorithms", Lewis and Denenberg,
       Harper Collins, 1991, pp 243-251.
  [3] "Self-adjusting Binary Search Trees" Sleator and Tarjan,
       JACM Volume 32, No 3, July 1985, pp 652-686.
  [4] "Data Structure and Algorithm Analysis", Mark Weiss,
       Benjamin Cummins, 1992, pp 119-130.
  [5] "Data Structures, Algorithms, and Performance", Derick Wood,
       Addison-Wesley, 1993, pp 367-375.

  The following code was written by Daniel Sleator, and is released
  in the public domain. It has been heavily modified by Carmelo Piccione,
72
  (cep@andrew.cmu.edu), to suit personal needs, 
73 74
*/

Rafaël Carré's avatar
Rafaël Carré committed
75
#include <stdlib.h>
76
#include <stdio.h>
77 78 79 80 81 82 83 84 85

#include "common.h"
#include "fatal.h"

#include "splaytree_types.h"
#include "splaytree.h"



86 87 88 89 90 91 92 93 94
splaynode_t * splay (void * key, splaynode_t * t, int * match_type, int (*compare)());
int free_splaynode(splaynode_t * splaynode, void (*free_key)());
void splay_traverse_helper (void (*func_ptr)(), splaynode_t * splaynode);
splaynode_t * splay_delete_helper(void * key, splaynode_t * t, int (*compare)(), void (*free_key)());
void splay_find_above_min_helper(void * max_key, void ** closest_key, splaynode_t * root, int (*compare)());
void splay_find_below_max_helper(void * max_key, void ** closest_key, splaynode_t * root, int (*compare)());
splaynode_t * new_splaynode(int type, void * key, void * data);
int splay_insert_node(splaynode_t * splaynode, splaytree_t * splaytree);
int splay_rec_size(splaynode_t * splaynode);
95 96 97

/* Creates a splay tree given a compare key function, copy key function, and free key function.
   Ah yes, the wonders of procedural programming */
98
splaytree_t * create_splaytree(int (*compare)(), void * (*copy_key)(), void (*free_key)()) {
99 100 101 102 103 104 105 106 107 108 109 110

  splaytree_t * splaytree;

  /* Allocate memory for the splaytree struct */
  if ((splaytree = (splaytree_t*)malloc(sizeof(splaytree_t))) == NULL)
    return NULL;

  /* Set struct entries */
  splaytree->root = NULL;
  splaytree->compare = compare;
  splaytree->copy_key = copy_key;
  splaytree->free_key = free_key;
111
  
112 113 114 115 116
  /* Return instantiated splay tree */
  return splaytree;
}

/* Destroys a splay tree */
117
int destroy_splaytree(splaytree_t * splaytree) {
118 119 120 121 122 123 124 125 126 127

  /* Null argument check */
  if (splaytree == NULL)
    return FAILURE;

  /* Recursively free all splaynodes in tree */
  free_splaynode(splaytree->root, splaytree->free_key);

  /* Free the splaytree struct itself */
  free(splaytree);
128
  
129 130 131 132 133 134
  /* Done, return success */
  return SUCCESS;

}

/* Recursively free all the splaynodes */
135
int free_splaynode(splaynode_t * splaynode, void (*free_key)()) {
136 137 138 139 140 141 142

  /* Ok if this happens, a recursive base case */
  if (splaynode == NULL)
    return SUCCESS;

  /* Free left node */
  free_splaynode(splaynode->left, free_key);
143
  
144 145
  /* Free right node */
  free_splaynode(splaynode->right, free_key);
146
  
147 148
  /* Free this node's key */
  free_key(splaynode->key);
149
  
150 151
  /* Note that the data pointers are not freed here.
     Should be freed with a splay traversal function */
152
  
153 154 155 156 157 158 159 160 161
  /* Free the splaynode structure itself */
  free(splaynode);
 
  /* Finished, return success */
  return SUCCESS;

}

/* Traverses the entire splay tree with the given function func_ptr */
162
void splay_traverse(void (*func_ptr)(), splaytree_t * splaytree) {
163 164 165 166

  /* Null argument check */

  if (splaytree == NULL)
167
    return; 
168
  if (func_ptr == NULL)
169 170
	return;
  
171 172 173 174 175 176 177
  /* Call recursive helper function */
  splay_traverse_helper(func_ptr, splaytree->root);

  return;
}

/* Helper function to traverse the entire splaytree */
178
void splay_traverse_helper (void (*func_ptr)(), splaynode_t * splaynode) {  
179 180 181 182 183 184 185

  /* Normal if this happens, its a base case of recursion */
  if (splaynode == NULL)
    return;

  /* Recursively traverse to the left */
  splay_traverse_helper(func_ptr, splaynode->left);
186 187
  
  
188 189
  /* Node is a of regular type, so its ok to perform the function on it */
  if (splaynode->type == REGULAR_NODE_TYPE)
190 191
  	func_ptr(splaynode->data);
  
192 193
  /* Node is of symbolic link type, do nothing */
  else if (splaynode->type == SYMBOLIC_NODE_TYPE)
194 195
	;
  
196 197 198
  /* Unknown node type */
  else
    ;
199
  
200 201 202 203 204 205 206 207
  /* Recursively traverse to the right */
  splay_traverse_helper(func_ptr, splaynode->right);

  /* Done */
  return;
}

/* Find the node corresponding to the given key in splaytree, return its data pointer */
208
void * splay_find(void * key, splaytree_t * splaytree) {
209 210 211 212 213

  splaynode_t * splaynode;
  int match_type;

  if (key == NULL)
214 215
	  return NULL;
  
216
  if (splaytree == NULL)
217 218
	  return NULL;
  
219
  splaynode = splaytree->root;
220
  
221 222 223
  /* Bring the targeted splay node to the top of the splaytree */
  splaynode = splay(key, splaynode, &match_type, splaytree->compare);
  splaytree->root = splaynode;
224 225
  
  
226
  /* We only want perfect matches, so return null when match isn't perfect */
227
  if (match_type == CLOSEST_MATCH) 
228 229 230 231
    return NULL;

  /* This shouldn't happen because of the match type check, but whatever */
  if (splaytree->root == NULL)
232 233
	  return NULL;
  
234 235
  /* Node is a regular type, return its data pointer */
  if (splaytree->root->type == REGULAR_NODE_TYPE) /* regular node */
236 237
  	return splaytree->root->data;
  
238 239
  /* If the node is a symlink, pursue one link */
  if (splaytree->root->type == SYMBOLIC_NODE_TYPE) /* symbolic node */
240 241 242
	return ((splaynode_t*)splaytree->root->data)->data;
    
  
243 244 245 246 247
  /* Unknown type */
  return NULL;
}

/* Gets the splaynode that the given key points to */
248
splaynode_t * get_splaynode_of(void * key, splaytree_t * splaytree) {
249 250 251

  splaynode_t * splaynode;
  int match_type;
252 253
  
  /* Null argument checks */	
254
  if (splaytree == NULL)
255 256
	  return NULL;
  
257
  if (key == NULL)
258 259
	  return NULL;
  
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  splaynode = splaytree->root;

  /* Find the splaynode */
  splaynode = splay(key, splaynode, &match_type, splaytree->compare);
  splaytree->root = splaynode;
 
  /* Only perfect matches are valid */
  if (match_type == CLOSEST_MATCH)
    return NULL;

  /* Return the perfect match splay node */
  return splaynode;
}

/* Finds the desired node, and changes the tree such that it is the root */
275
splaynode_t * splay (void * key, splaynode_t * t, int * match_type, int (*compare)()) {
276 277
  
/* Simple top down splay, not requiring key to be in the tree t. 
278 279 280 281
   What it does is described above. */
 
    splaynode_t N, *l, *r, *y;
    *match_type = CLOSEST_MATCH;
282 283
  
	if (t == NULL) return t;
284 285
    N.left = N.right = NULL;
    l = r = &N;
286
  
287
    for (;;) {
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
	if (compare(key, t->key) < 0) {
	    if (t->left == NULL) break;
	    if (compare(key, t->left->key) < 0) {
		y = t->left;                           /* rotate right */
		t->left = y->right;
		y->right = t;
		t = y;
		if (t->left == NULL) break;
	    }
	    r->left = t;                               /* link right */
	    r = t;
	    t = t->left;
	} else if (compare(key, t->key) > 0) {
	    if (t->right == NULL) break;
	    if (compare(key, t->right->key) > 0) {
		y = t->right;                          /* rotate left */
		t->right = y->left;
		y->left = t;
		t = y;
		if (t->right == NULL) break;
	    }
	    l->right = t;                              /* link left */
	    l = t;
	    t = t->right;
	} else {
	  *match_type = PERFECT_MATCH;
	  break;
	}
316 317 318 319 320
    }
    l->right = t->left;                                /* assemble */
    r->left = t->right;
    t->left = N.right;
    t->right = N.left;
321
    
322 323 324 325 326 327 328
    return t;

    //return NULL;
}

/* Deletes a splay node from a splay tree. If the node doesn't exist
   then nothing happens */
329
int splay_delete(void * key, splaytree_t * splaytree) {
330
  
331 332 333 334
  splaynode_t * splaynode;

  /* Use helper function to delete the node and return the resulting tree */
  if ((splaynode = splay_delete_helper(key, splaytree->root, splaytree->compare, splaytree->free_key)) == NULL)
335 336
	  return FAILURE;
  
337 338
  /* Set new splaytree root equal to the returned splaynode after deletion */
  splaytree->root = splaynode;
339
  
340 341 342 343 344
  /* Finished, no errors */
  return SUCCESS;
}

/* Deletes a splay node */
345
splaynode_t * splay_delete_helper(void * key, splaynode_t * splaynode, int (*compare)(), void (*free_key)()) {
346
	
347 348
    splaynode_t * new_root;
    int match_type;
349 350 351 352 353
	
	/* Argument check */	
    if (splaynode == NULL) 
		return NULL;
	
354
    splaynode = splay(key, splaynode, &match_type, compare);
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
	
	/* If entry wasn't found, quit here */
	if (match_type == CLOSEST_MATCH) 
		return NULL;
	
	/* If the targeted node's left pointer is null, then set the new root
	   equal to the splaynode's right child */
	if (splaynode->left == NULL) {
	    new_root = splaynode->right;
	} 
	
	/* Otherwise, do something I don't currently understand */
	else {
	    new_root = splay(key, splaynode->left, &match_type, compare);
	    new_root->right = splaynode->right;
	}

	/* Set splay nodes children pointers to null */
	splaynode->left = splaynode->right = NULL;
	
	/* Free the splaynode (and only this node since its children are now empty */
	free_splaynode(splaynode, free_key);
	
	/* Return the resulting tree */
	return new_root;
	
381 382 383
}

/* Create a new splay node type */
384
splaynode_t * new_splaynode(int type, void * key, void * data) {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	splaynode_t * splaynode;	
	/* Argument checks */
	if (data == NULL)
		return NULL;
	
	if (key == NULL)
		return NULL;
	
	/* Creates the new splay node struct */
	if ((splaynode = (splaynode_t*)malloc(sizeof(splaynode_t))) == NULL)
		return NULL;
	
	splaynode->data = data;
	splaynode->type = type;
	splaynode->key = key;
	
	/* Return the new splay node */
	return splaynode;
403 404 405
}

/* Inserts a link into the splay tree */
406
int splay_insert_link(const void * alias_key, void * orig_key, splaytree_t * splaytree) {
407 408 409 410

   splaynode_t * splaynode, * data_node;
   void * key_clone;

411
   /* Null arguments */	
412
   if (splaytree == NULL)
413 414
		return FAILURE;
   
415
   if (alias_key == NULL)
416
	   	return FAILURE;
417 418

   if (orig_key == NULL)
419 420
	   	return FAILURE;
   
421 422
   /* Find the splaynode corresponding to the original key */
   if ((data_node = get_splaynode_of(orig_key, splaytree)) == NULL)
423 424
	   return FAILURE;
   
425 426
   /* Create a new splay node of symbolic link type */
   if ((splaynode = new_splaynode(SYMBOLIC_NODE_TYPE, (key_clone = splaytree->copy_key(alias_key)), data_node)) == NULL) {
427 428
		splaytree->free_key(key_clone);
		return OUTOFMEM_ERROR;
429 430 431 432 433 434 435
   }

   /* Insert the splaynode into the given splaytree */
   if ((splay_insert_node(splaynode, splaytree)) < 0) {
     splaynode->left=splaynode->right = NULL;
     free_splaynode(splaynode, splaytree->free_key);
     return FAILURE;
436 437
   }		
	
438 439
   /* Done, return success */
   return SUCCESS;
440
}	
441 442

/* Inserts 'data' into the 'splaytree' paired with the passed 'key' */
443
int splay_insert(void * data, void * key, splaytree_t * splaytree) {
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	splaynode_t * splaynode;
	void * key_clone;
	
	/* Null argument checks */
	if (splaytree == NULL) {
	    return FAILURE;
	}
	
	if (key == NULL)
		return FAILURE;
	
	/* Clone the key argument */
	key_clone = splaytree->copy_key(key);

	/* Create a new splaynode (of regular type) */
	if ((splaynode = new_splaynode(REGULAR_NODE_TYPE, key_clone, data)) == NULL) {
		splaytree->free_key(key_clone);
		return OUTOFMEM_ERROR;		
	}
       
	
	/* Inserts the splaynode into the splaytree */
	if (splay_insert_node(splaynode, splaytree) < 0) {
	  splaynode->left=splaynode->right=NULL;
	  free_splaynode(splaynode, splaytree->free_key);
	  return FAILURE;		
	}	
     

	return SUCCESS;
475 476 477
}

/* Helper function to insert splaynodes into the splaytree */
478
int splay_insert_node(splaynode_t * splaynode, splaytree_t * splaytree) {
479 480 481 482
  int match_type;
  int cmpval;
  void * key;
  splaynode_t * t;
483
	
484 485 486 487 488
  /* Null argument checks */
  if (splaytree == NULL)
    return FAILURE;

  if (splaynode == NULL)
489 490
	return FAILURE;
  
491
  key = splaynode->key;
492 493
  
  t = splaytree->root; 
494 495 496 497


  /* Root is null, insert splaynode here */
  if (t == NULL) {
498 499 500
	splaynode->left = splaynode->right = NULL;
	splaytree->root = splaynode;
	return SUCCESS;
501 502

  }
503
  
504
  t = splay(key, t, &match_type, splaytree->compare);
505
  
506
  if ((cmpval = splaytree->compare(key,t->key)) < 0) {
507 508 509 510 511
	splaynode->left = t->left;
	splaynode->right = t;
	t->left = NULL;
	splaytree->root = splaynode;
	return SUCCESS;
512

513
  } 
514 515

  else if (cmpval > 0) {
516 517 518 519 520 521 522
	splaynode->right = t->right;
	splaynode->left = t;
	t->right = NULL; 
	splaytree->root = splaynode;
	return SUCCESS;
   } 
   
523 524
   /* Item already exists in tree, don't reinsert */
  else {
525
    
526 527 528 529 530
    return FAILURE;
  }
}

/* Returns the 'maximum' key that is less than the given key in the splaytree */
531
void * splay_find_below_max(void * key, splaytree_t * splaytree) {
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
	
	void * closest_key;
	
	if (splaytree == NULL)
		return NULL;
	if (splaytree->root == NULL)
		return NULL;
	if (key == NULL)
		return NULL;
	
	closest_key = NULL;
	
	splay_find_below_max_helper(key, &closest_key, splaytree->root, splaytree->compare);

	if (closest_key == NULL) return NULL;
	return splay_find(closest_key, splaytree);
548 549 550 551
}


/* Returns the 'minimum' key that is greater than the given key in the splaytree */
552
void * splay_find_above_min(void * key, splaytree_t * splaytree) {
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
	
	void * closest_key;
	
	if (splaytree == NULL)
		return NULL;
	if (splaytree->root == NULL)
		return NULL;
	if (key == NULL)
		return NULL;
	closest_key = NULL;
	
	splay_find_above_min_helper(key, &closest_key, splaytree->root, splaytree->compare);

	if (closest_key == NULL) { 
		return NULL;
	}
	
	return splay_find(closest_key, splaytree);
571 572 573
}

/* Helper function */
574
void splay_find_below_max_helper(void * min_key, void ** closest_key, splaynode_t * root, int (*compare)()) {
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
		/* Empty root, return*/	
		if (root == NULL)
			return;
			
		/* The root key is less than the previously found closest key.
		   Also try to make the key non null if the value is less than the max key */
		
		if ((*closest_key == NULL) || (compare(root->key, *closest_key) < 0)) {
			
			/*  The root key is less than the given max key, so this is the
				smallest change from the given max key */
			if (compare(root->key, min_key) > 0) {
				
				*closest_key = root->key;
				
				/* Look right again in case even a greater key exists that is 
				   still less than the given max key */
				splay_find_below_max_helper(min_key, closest_key, root->left, compare);
			}
			
			/* The root key is greater than the given max key, and greater than 
			   the closest key, so search left */
			else {
				splay_find_below_max_helper(min_key, closest_key, root->right, compare);				
			}	
		}	
		
		/* The root key is less than the found closest key, search right */
		else {
				splay_find_below_max_helper(min_key, closest_key, root->left, compare);				
		}
	
608 609 610
}

/* Helper function */
611
void splay_find_above_min_helper(void * max_key, void ** closest_key, splaynode_t * root, int (*compare)()) {
612

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
		/* Empty root, stop */	
		if (root == NULL)
			return;
			
		/* The root key is greater than the previously found closest key.
		   Also try to make the key non null if the value is less than the min key */
		
		if ((*closest_key == NULL) || (compare(root->key, *closest_key) > 0)) {
			
			/*  The root key is greater than the given min key, so this is the
				smallest change from the given min key */
			if (compare(root->key, max_key) < 0) {
				
				*closest_key = root->key;
				
			   /* Look left again in case even a smaller key exists that is 
				  still greater than the given min key */
				splay_find_above_min_helper(max_key, closest_key, root->right, compare);
			}
			
			/* The root key is less than the given min key, and less than 
			   the closest key, so search right */
			else {
				splay_find_above_min_helper(max_key, closest_key, root->left, compare);				
			}	
		}	
		
		/* The root key is greater than the found closest key, search left */
		else {
				splay_find_above_min_helper(max_key, closest_key, root->right, compare);				
		}
}	
645 646

/* Find the minimum entry of the splay tree */
647
void * splay_find_min(splaytree_t * t) {
648

649 650 651 652 653 654 655 656 657 658 659 660 661
	splaynode_t * splaynode;
	
	if (t == NULL)
		return NULL;
	if (t->root == NULL)
		return NULL;
	
	splaynode = t->root;
	
	while (splaynode->left != NULL)
		splaynode= splaynode->left;
	
	return splaynode->data;
662 663 664 665
}


/* Find the maximum entry of the splay tree */
666
void * splay_find_max(splaytree_t * t) {
667

668 669 670 671 672 673 674 675 676 677 678 679 680 681
	splaynode_t * splaynode;
	
	if (t == NULL)
		return NULL;
	if (t->root == NULL)
		return NULL;
	
	splaynode = t->root;
	 
	while (splaynode->right != NULL) {
	  printf("data:%d\n", *(int*)splaynode->key);
		splaynode = splaynode->right;
	}
	return splaynode->data;
682 683
}

684
int splay_size(splaytree_t * t) {
685

686 687 688 689 690 691 692
	if (t == NULL)
	  return 0;
	if (t->root == NULL)
	  return 0;
	
	return splay_rec_size(t->root);
	 
693 694
}

695
int splay_rec_size(splaynode_t * splaynode) {
696 697 698 699 700 701 702

  if (!splaynode)
    return 0;

  return 1 + splay_rec_size(splaynode->left) + splay_rec_size(splaynode->right);

}