This commit was manufactured by cvs2svn to create tag
[Samba/gbeck.git] / source / ubiqx / ubi_SplayTree.c
blobad8d568658d31b7283bb8a1c528dc484f951aca3
1 /* ========================================================================== **
2 * ubi_SplayTree.c
4 * Copyright (C) 1993-1998 by Christopher R. Hertel
6 * Email: crh@ubiqx.mn.org
7 * -------------------------------------------------------------------------- **
9 * This module implements "splay" trees. Splay trees are binary trees
10 * that are rearranged (splayed) whenever a node is accessed. The
11 * splaying process *tends* to make the tree bushier (improves balance),
12 * and the nodes that are accessed most frequently *tend* to be closer to
13 * the top.
15 * References: "Self-Adjusting Binary Search Trees", by Daniel Sleator and
16 * Robert Tarjan. Journal of the Association for Computing
17 * Machinery Vol 32, No. 3, July 1985 pp. 652-686
19 * See also: http://www.cs.cmu.edu/~sleator/
21 * -------------------------------------------------------------------------- **
23 * This library is free software; you can redistribute it and/or
24 * modify it under the terms of the GNU Library General Public
25 * License as published by the Free Software Foundation; either
26 * version 2 of the License, or (at your option) any later version.
28 * This library is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
31 * Library General Public License for more details.
33 * You should have received a copy of the GNU Library General Public
34 * License along with this library; if not, write to the Free
35 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
37 * -------------------------------------------------------------------------- **
39 * Log: ubi_SplayTree.c,v
40 * Revision 4.4 1998/06/04 21:29:27 crh
41 * Upper-cased defined constants (eg UBI_BINTREE_H) in some header files.
42 * This is more "standard", and is what people expect. Weird, eh?
44 * Revision 4.3 1998/06/03 17:45:05 crh
45 * Further fiddling with sys_include.h. It's now in ubi_BinTree.h which is
46 * included by all of the binary tree files.
48 * Also fixed some warnings produced by lint on Irix 6.2, which doesn't seem
49 * to like syntax like this:
51 * if( (a = b) )
53 * The fix was to change lines like the above to:
55 * if( 0 != (a=b) )
57 * Which means the same thing.
59 * Reminder: Some of the ubi_tr* macros in ubi_BinTree.h are redefined in
60 * ubi_AVLtree.h and ubi_SplayTree.h. This allows easy swapping
61 * of tree types by simply changing a header. Unfortunately, the
62 * macro redefinitions in ubi_AVLtree.h and ubi_SplayTree.h will
63 * conflict if used together. You must either choose a single tree
64 * type, or use the underlying function calls directly. Compare
65 * the two header files for more information.
67 * Revision 4.2 1998/06/02 01:29:14 crh
68 * Changed ubi_null.h to sys_include.h to make it more generic.
70 * Revision 4.1 1998/05/20 04:37:54 crh
71 * The C file now includes ubi_null.h. See ubi_null.h for more info.
73 * Revision 4.0 1998/03/10 03:41:33 crh
74 * Minor comment changes. The revision number is now 4.0 to match the
75 * BinTree and AVLtree modules.
77 * Revision 2.7 1998/01/24 06:37:08 crh
78 * Added a URL for more information.
80 * Revision 2.6 1997/12/23 04:01:12 crh
81 * In this version, all constants & macros defined in the header file have
82 * the ubi_tr prefix. Also cleaned up anything that gcc complained about
83 * when run with '-pedantic -fsyntax-only -Wall'.
85 * Revision 2.5 1997/07/26 04:15:42 crh
86 * + Cleaned up a few minor syntax annoyances that gcc discovered for me.
87 * + Changed ubi_TRUE and ubi_FALSE to ubi_trTRUE and ubi_trFALSE.
89 * Revision 2.4 1997/06/03 04:42:21 crh
90 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid causing
91 * problems.
93 * Revision 2.3 1995/10/03 22:19:07 CRH
94 * Ubisized!
95 * Also, added the function ubi_sptSplay().
97 * Revision 2.1 95/03/09 23:54:42 CRH
98 * Added the ModuleID static string and function. These modules are now
99 * self-identifying.
101 * Revision 2.0 95/02/27 22:34:46 CRH
102 * This module was updated to match the interface changes made to the
103 * ubi_BinTree module. In particular, the interface to the Locate() function
104 * has changed. See ubi_BinTree for more information on changes and new
105 * functions.
107 * The revision number was also upped to match ubi_BinTree.
109 * Revision 1.1 93/10/18 20:35:16 CRH
110 * I removed the hard-coded logical device names from the include file
111 * specifications. CRH
113 * Revision 1.0 93/10/15 23:00:15 CRH
114 * With this revision, I have added a set of #define's that provide a single,
115 * standard API to all existing tree modules. Until now, each of the three
116 * existing modules had a different function and typedef prefix, as follows:
118 * Module Prefix
119 * ubi_BinTree ubi_bt
120 * ubi_AVLtree ubi_avl
121 * ubi_SplayTree ubi_spt
123 * To further complicate matters, only those portions of the base module
124 * (ubi_BinTree) that were superceeded in the new module had the new names.
125 * For example, if you were using ubi_SplayTree, the locate function was
126 * called "ubi_sptLocate", but the next and previous functions remained
127 * "ubi_btNext" and "ubi_btPrev".
129 * This was not too terrible if you were familiar with the modules and knew
130 * exactly which tree model you wanted to use. If you wanted to be able to
131 * change modules (for speed comparisons, etc), things could get messy very
132 * quickly.
134 * So, I have added a set of defined names that get redefined in any of the
135 * descendant modules. To use this standardized interface in your code,
136 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
137 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
138 * datatype names for the module that you are using. Just remember to
139 * include the header for that module in your program file. Because these
140 * names are handled by the preprocessor, there is no added run-time
141 * overhead.
143 * Note that the original names do still exist, and can be used if you wish
144 * to write code directly to a specific module. This should probably only be
145 * done if you are planning to implement a new descendant type, such as
146 * red/black trees. CRH
148 * Revision 0.1 93/04/25 22:03:32 CRH
149 * Simply changed the <exec/types.h> #include reference the .c file to
150 * use <stdlib.h> instead. The latter is portable, the former is not.
152 * Revision 0.0 93/04/21 23:05:52 CRH
153 * Initial version, written by Christopher R. Hertel.
154 * This module implements Splay Trees using the ubi_BinTree module as a basis.
156 * ========================================================================== **
159 #include "ubi_SplayTree.h" /* Header for THIS module. */
161 /* ========================================================================== **
162 * Static data.
165 static char ModuleID[] = "ubi_SplayTree\n\
166 \tRevision: 4.4 \n\
167 \tDate: 1998/06/04 21:29:27 \n\
168 \tAuthor: crh \n";
171 /* ========================================================================== **
172 * Private functions...
175 static void Rotate( ubi_btNodePtr p )
176 /* ------------------------------------------------------------------------ **
177 * This function performs a single rotation, moving node *p up one level
178 * in the tree.
180 * Input: p - a pointer to an ubi_btNode in a tree.
182 * Output: None.
184 * Notes: This implements a single rotation in either direction (left
185 * or right). This is the basic building block of all splay
186 * tree rotations.
187 * ------------------------------------------------------------------------ **
190 ubi_btNodePtr parentp;
191 ubi_btNodePtr tmp;
192 char way;
193 char revway;
195 parentp = p->Link[ubi_trPARENT]; /* Find parent. */
197 if( parentp ) /* If no parent, then we're already the root. */
199 way = p->gender;
200 revway = ubi_trRevWay(way);
201 tmp = p->Link[(int)revway];
203 parentp->Link[(int)way] = tmp;
204 if( tmp )
206 tmp->Link[ubi_trPARENT] = parentp;
207 tmp->gender = way;
210 tmp = parentp->Link[ubi_trPARENT];
211 p->Link[ubi_trPARENT] = tmp;
212 p->gender = parentp->gender;
213 if( tmp )
214 tmp->Link[(int)(p->gender)] = p;
216 parentp->Link[ubi_trPARENT] = p;
217 parentp->gender = revway;
218 p->Link[(int)revway] = parentp;
220 } /* Rotate */
222 static ubi_btNodePtr Splay( ubi_btNodePtr SplayWithMe )
223 /* ------------------------------------------------------------------------ **
224 * Move the node indicated by SplayWithMe to the root of the tree by
225 * splaying the tree.
227 * Input: SplayWithMe - A pointer to an ubi_btNode within a tree.
229 * Output: A pointer to the root of the splay tree (i.e., the same as
230 * SplayWithMe).
231 * ------------------------------------------------------------------------ **
234 ubi_btNodePtr parent;
236 while( NULL != (parent = SplayWithMe->Link[ubi_trPARENT]) )
238 if( parent->gender == SplayWithMe->gender ) /* Zig-Zig */
239 Rotate( parent );
240 else
242 if( ubi_trEQUAL != parent->gender ) /* Zig-Zag */
243 Rotate( SplayWithMe );
245 Rotate( SplayWithMe ); /* Zig */
246 } /* while */
247 return( SplayWithMe );
248 } /* Splay */
250 /* ========================================================================== **
251 * Exported utilities.
254 ubi_trBool ubi_sptInsert( ubi_btRootPtr RootPtr,
255 ubi_btNodePtr NewNode,
256 ubi_btItemPtr ItemPtr,
257 ubi_btNodePtr *OldNode )
258 /* ------------------------------------------------------------------------ **
259 * This function uses a non-recursive algorithm to add a new element to the
260 * splay tree.
262 * Input: RootPtr - a pointer to the ubi_btRoot structure that indicates
263 * the root of the tree to which NewNode is to be added.
264 * NewNode - a pointer to an ubi_btNode structure that is NOT
265 * part of any tree.
266 * ItemPtr - A pointer to the sort key that is stored within
267 * *NewNode. ItemPtr MUST point to information stored
268 * in *NewNode or an EXACT DUPLICATE. The key data
269 * indicated by ItemPtr is used to place the new node
270 * into the tree.
271 * OldNode - a pointer to an ubi_btNodePtr. When searching
272 * the tree, a duplicate node may be found. If
273 * duplicates are allowed, then the new node will
274 * be simply placed into the tree. If duplicates
275 * are not allowed, however, then one of two things
276 * may happen.
277 * 1) if overwritting *is not* allowed, this
278 * function will return FALSE (indicating that
279 * the new node could not be inserted), and
280 * *OldNode will point to the duplicate that is
281 * still in the tree.
282 * 2) if overwritting *is* allowed, then this
283 * function will swap **OldNode for *NewNode.
284 * In this case, *OldNode will point to the node
285 * that was removed (thus allowing you to free
286 * the node).
287 * ** If you are using overwrite mode, ALWAYS **
288 * ** check the return value of this parameter! **
289 * Note: You may pass NULL in this parameter, the
290 * function knows how to cope. If you do this,
291 * however, there will be no way to return a
292 * pointer to an old (ie. replaced) node (which is
293 * a problem if you are using overwrite mode).
295 * Output: a boolean value indicating success or failure. The function
296 * will return FALSE if the node could not be added to the tree.
297 * Such failure will only occur if duplicates are not allowed,
298 * nodes cannot be overwritten, AND a duplicate key was found
299 * within the tree.
300 * ------------------------------------------------------------------------ **
303 ubi_btNodePtr OtherP;
305 if( !(OldNode) )
306 OldNode = &OtherP;
308 if( ubi_btInsert( RootPtr, NewNode, ItemPtr, OldNode ) )
310 RootPtr->root = Splay( NewNode );
311 return( ubi_trTRUE );
314 /* Splay the unreplacable, duplicate keyed, unique, old node. */
315 RootPtr->root = Splay( (*OldNode) );
316 return( ubi_trFALSE );
317 } /* ubi_sptInsert */
319 ubi_btNodePtr ubi_sptRemove( ubi_btRootPtr RootPtr, ubi_btNodePtr DeadNode )
320 /* ------------------------------------------------------------------------ **
321 * This function removes the indicated node from the tree.
323 * Input: RootPtr - A pointer to the header of the tree that contains
324 * the node to be removed.
325 * DeadNode - A pointer to the node that will be removed.
327 * Output: This function returns a pointer to the node that was removed
328 * from the tree (ie. the same as DeadNode).
330 * Note: The node MUST be in the tree indicated by RootPtr. If not,
331 * strange and evil things will happen to your trees.
332 * ------------------------------------------------------------------------ **
335 ubi_btNodePtr p;
337 (void)Splay( DeadNode ); /* Move dead node to root. */
338 if( NULL != (p = DeadNode->Link[ubi_trLEFT]) )
339 { /* If left subtree exists... */
340 ubi_btNodePtr q = DeadNode->Link[ubi_trRIGHT];
342 p->Link[ubi_trPARENT] = NULL; /* Left subtree node becomes root.*/
343 p->gender = ubi_trPARENT;
344 p = ubi_btLast( p ); /* Find rightmost left node... */
345 p->Link[ubi_trRIGHT] = q; /* ...attach right tree. */
346 if( q )
347 q->Link[ubi_trPARENT] = p;
348 RootPtr->root = Splay( p ); /* Resplay at p. */
350 else
352 if( NULL != (p = DeadNode->Link[ubi_trRIGHT]) )
353 { /* No left, but right subtree exists... */
354 p->Link[ubi_trPARENT] = NULL; /* Right subtree root becomes... */
355 p->gender = ubi_trPARENT; /* ...overall tree root. */
356 RootPtr->root = p;
358 else
359 RootPtr->root = NULL; /* No subtrees => empty tree. */
362 (RootPtr->count)--; /* Decrement node count. */
363 return( DeadNode ); /* Return pointer to pruned node. */
364 } /* ubi_sptRemove */
366 ubi_btNodePtr ubi_sptLocate( ubi_btRootPtr RootPtr,
367 ubi_btItemPtr FindMe,
368 ubi_trCompOps CompOp )
369 /* ------------------------------------------------------------------------ **
370 * The purpose of ubi_btLocate() is to find a node or set of nodes given
371 * a target value and a "comparison operator". The Locate() function is
372 * more flexible and (in the case of trees that may contain dupicate keys)
373 * more precise than the ubi_btFind() function. The latter is faster,
374 * but it only searches for exact matches and, if the tree contains
375 * duplicates, Find() may return a pointer to any one of the duplicate-
376 * keyed records.
378 * Input:
379 * RootPtr - A pointer to the header of the tree to be searched.
380 * FindMe - An ubi_btItemPtr that indicates the key for which to
381 * search.
382 * CompOp - One of the following:
383 * CompOp Return a pointer to the node with
384 * ------ ---------------------------------
385 * ubi_trLT - the last key value that is less
386 * than FindMe.
387 * ubi_trLE - the first key matching FindMe, or
388 * the last key that is less than
389 * FindMe.
390 * ubi_trEQ - the first key matching FindMe.
391 * ubi_trGE - the first key matching FindMe, or the
392 * first key greater than FindMe.
393 * ubi_trGT - the first key greater than FindMe.
394 * Output:
395 * A pointer to the node matching the criteria listed above under
396 * CompOp, or NULL if no node matched the criteria.
398 * Notes:
399 * In the case of trees with duplicate keys, Locate() will behave as
400 * follows:
402 * Find: 3 Find: 3
403 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
404 * ^ ^ ^ ^ ^
405 * LT EQ GT LE GE
407 * That is, when returning a pointer to a node with a key that is LESS
408 * THAN the target key (FindMe), Locate() will return a pointer to the
409 * LAST matching node.
410 * When returning a pointer to a node with a key that is GREATER
411 * THAN the target key (FindMe), Locate() will return a pointer to the
412 * FIRST matching node.
414 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
415 * ------------------------------------------------------------------------ **
418 ubi_btNodePtr p;
420 p = ubi_btLocate( RootPtr, FindMe, CompOp );
421 if( p )
422 RootPtr->root = Splay( p );
423 return( p );
424 } /* ubi_sptLocate */
426 ubi_btNodePtr ubi_sptFind( ubi_btRootPtr RootPtr,
427 ubi_btItemPtr FindMe )
428 /* ------------------------------------------------------------------------ **
429 * This function performs a non-recursive search of a tree for any node
430 * matching a specific key.
432 * Input:
433 * RootPtr - a pointer to the header of the tree to be searched.
434 * FindMe - a pointer to the key value for which to search.
436 * Output:
437 * A pointer to a node with a key that matches the key indicated by
438 * FindMe, or NULL if no such node was found.
440 * Note: In a tree that allows duplicates, the pointer returned *might
441 * not* point to the (sequentially) first occurance of the
442 * desired key. In such a tree, it may be more useful to use
443 * ubi_sptLocate().
444 * ------------------------------------------------------------------------ **
447 ubi_btNodePtr p;
449 p = ubi_btFind( RootPtr, FindMe );
450 if( p )
451 RootPtr->root = Splay( p );
452 return( p );
453 } /* ubi_sptFind */
455 void ubi_sptSplay( ubi_btRootPtr RootPtr,
456 ubi_btNodePtr SplayMe )
457 /* ------------------------------------------------------------------------ **
458 * This function allows you to splay the tree at a given node, thus moving
459 * the node to the top of the tree.
461 * Input:
462 * RootPtr - a pointer to the header of the tree to be splayed.
463 * SplayMe - a pointer to a node within the tree. This will become
464 * the new root node.
465 * Output: None.
467 * Notes: This is an uncharacteristic function for this group of modules
468 * in that it provides access to the internal balancing routines,
469 * which would normally be hidden.
470 * Splaying the tree will not damage it (assuming that I've done
471 * *my* job), but there is overhead involved. I don't recommend
472 * that you use this function unless you understand the underlying
473 * Splay Tree principles involved.
474 * ------------------------------------------------------------------------ **
477 RootPtr->root = Splay( SplayMe );
478 } /* ubi_sptSplay */
480 int ubi_sptModuleID( int size, char *list[] )
481 /* ------------------------------------------------------------------------ **
482 * Returns a set of strings that identify the module.
484 * Input: size - The number of elements in the array <list>.
485 * list - An array of pointers of type (char *). This array
486 * should, initially, be empty. This function will fill
487 * in the array with pointers to strings.
488 * Output: The number of elements of <list> that were used. If this value
489 * is less than <size>, the values of the remaining elements are
490 * not guaranteed.
492 * Notes: Please keep in mind that the pointers returned indicate strings
493 * stored in static memory. Don't free() them, don't write over
494 * them, etc. Just read them.
495 * ------------------------------------------------------------------------ **
498 if( size > 0 )
500 list[0] = ModuleID;
501 if( size > 1 )
502 return( 1 + ubi_btModuleID( --size, &(list[1]) ) );
503 return( 1 );
505 return( 0 );
506 } /* ubi_sptModuleID */
508 /* ================================ The End ================================= */