1 /* ========================================================================== **
4 * Copyright (C) 1993-1995 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
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 * -------------------------------------------------------------------------- **
21 * This library is free software; you can redistribute it and/or
22 * modify it under the terms of the GNU Library General Public
23 * License as published by the Free Software Foundation; either
24 * version 2 of the License, or (at your option) any later version.
26 * This library is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
29 * Library General Public License for more details.
31 * You should have received a copy of the GNU Library General Public
32 * License along with this library; if not, write to the Free
33 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 * -------------------------------------------------------------------------- **
37 * Revision 2.5 1997/07/26 04:15:42 crh
38 * + Cleaned up a few minor syntax annoyances that gcc discovered for me.
39 * + Changed ubi_TRUE and ubi_FALSE to ubi_trTRUE and ubi_trFALSE.
41 * Revision 2.4 1997/06/03 04:42:21 crh
42 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid causing
45 * Revision 2.3 1995/10/03 22:19:07 CRH
47 * Also, added the function ubi_sptSplay().
49 * Revision 2.1 95/03/09 23:54:42 CRH
50 * Added the ModuleID static string and function. These modules are now
53 * Revision 2.0 95/02/27 22:34:46 CRH
54 * This module was updated to match the interface changes made to the
55 * ubi_BinTree module. In particular, the interface to the Locate() function
56 * has changed. See ubi_BinTree for more information on changes and new
59 * The revision number was also upped to match ubi_BinTree.
61 * Revision 1.1 93/10/18 20:35:16 CRH
62 * I removed the hard-coded logical device names from the include file
65 * Revision 1.0 93/10/15 23:00:15 CRH
66 * With this revision, I have added a set of #define's that provide a single,
67 * standard API to all existing tree modules. Until now, each of the three
68 * existing modules had a different function and typedef prefix, as follows:
73 * ubi_SplayTree ubi_spt
75 * To further complicate matters, only those portions of the base module
76 * (ubi_BinTree) that were superceeded in the new module had the new names.
77 * For example, if you were using ubi_AVLtree, the AVL node structure was
78 * named "ubi_avlNode", but the root structure was still "ubi_btRoot". Using
79 * SplayTree, the locate function was called "ubi_sptLocate", but the next
80 * and previous functions remained "ubi_btNext" and "ubi_btPrev".
82 * This was not too terrible if you were familiar with the modules and knew
83 * exactly which tree model you wanted to use. If you wanted to be able to
84 * change modules (for speed comparisons, etc), things could get messy very
87 * So, I have added a set of defined names that get redefined in any of the
88 * descendant modules. To use this standardized interface in your code,
89 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
90 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
91 * datatype names for the module that you are using. Just remember to
92 * include the header for that module in your program file. Because these
93 * names are handled by the preprocessor, there is no added run-time
96 * Note that the original names do still exist, and can be used if you wish
97 * to write code directly to a specific module. This should probably only be
98 * done if you are planning to implement a new descendant type, such as
99 * red/black trees. CRH
101 * Revision 0.1 93/04/25 22:03:32 CRH
102 * Simply changed the <exec/types.h> #include reference the .c file to
103 * use <stdlib.h> instead. The latter is portable, the former is not.
105 * Revision 0.0 93/04/21 23:05:52 CRH
106 * Initial version, written by Christopher R. Hertel.
107 * This module implements Splay Trees using the ubi_BinTree module as a basis.
109 * ========================================================================== **
112 #include <stdlib.h> /* Defines NULL for us. */
113 #include "ubi_SplayTree.h" /* Header for THIS module. */
115 /* ========================================================================== **
119 static char ModuleID
[] = "ubi_SplayTree\n\
121 \tDate: 1997/07/26 04:15:42\n\
125 /* ========================================================================== **
126 * Private functions...
129 static void Rotate( ubi_btNodePtr p
)
130 /* ------------------------------------------------------------------------ **
131 * This function performs a single rotation, moving node *p up one level
134 * Input: p - a pointer to an ubi_btNode in a tree.
138 * Notes: This implements a single rotation in either direction (left
139 * or right). This is the basic building block of all splay
141 * ------------------------------------------------------------------------ **
144 ubi_btNodePtr parentp
;
149 parentp
= p
->Link
[PARENT
]; /* Find parent. */
151 if( parentp
) /* If no parent, then we're already the root. */
154 revway
= RevWay(way
);
155 tmp
= p
->Link
[revway
];
157 parentp
->Link
[way
] = tmp
;
160 tmp
->Link
[PARENT
] = parentp
;
164 tmp
= parentp
->Link
[PARENT
];
165 p
->Link
[PARENT
] = tmp
;
166 p
->gender
= parentp
->gender
;
168 tmp
->Link
[p
->gender
] = p
;
170 parentp
->Link
[PARENT
] = p
;
171 parentp
->gender
= revway
;
172 p
->Link
[revway
] = parentp
;
176 static ubi_btNodePtr
Splay( ubi_btNodePtr SplayWithMe
)
177 /* ------------------------------------------------------------------------ **
178 * Move the node indicated by SplayWithMe to the root of the tree by
181 * Input: SplayWithMe - A pointer to an ubi_btNode within a tree.
183 * Output: A pointer to the root of the splay tree (i.e., the same as
185 * ------------------------------------------------------------------------ **
188 ubi_btNodePtr parent
;
190 while( (parent
= SplayWithMe
->Link
[PARENT
]) )
192 if( parent
->gender
== SplayWithMe
->gender
) /* Zig-Zig */
196 if( EQUAL
!= parent
->gender
) /* Zig-Zag */
197 Rotate( SplayWithMe
);
199 Rotate( SplayWithMe
); /* Zig */
201 return( SplayWithMe
);
204 /* ========================================================================== **
205 * Exported utilities.
208 ubi_trBool
ubi_sptInsert( ubi_btRootPtr RootPtr
,
209 ubi_btNodePtr NewNode
,
210 ubi_btItemPtr ItemPtr
,
211 ubi_btNodePtr
*OldNode
)
212 /* ------------------------------------------------------------------------ **
213 * This function uses a non-recursive algorithm to add a new element to the
216 * Input: RootPtr - a pointer to the ubi_btRoot structure that indicates
217 * the root of the tree to which NewNode is to be added.
218 * NewNode - a pointer to an ubi_btNode structure that is NOT
220 * ItemPtr - A pointer to the sort key that is stored within
221 * *NewNode. ItemPtr MUST point to information stored
222 * in *NewNode or an EXACT DUPLICATE. The key data
223 * indicated by ItemPtr is used to place the new node
225 * OldNode - a pointer to an ubi_btNodePtr. When searching
226 * the tree, a duplicate node may be found. If
227 * duplicates are allowed, then the new node will
228 * be simply placed into the tree. If duplicates
229 * are not allowed, however, then one of two things
231 * 1) if overwritting *is not* allowed, this
232 * function will return FALSE (indicating that
233 * the new node could not be inserted), and
234 * *OldNode will point to the duplicate that is
236 * 2) if overwritting *is* allowed, then this
237 * function will swap **OldNode for *NewNode.
238 * In this case, *OldNode will point to the node
239 * that was removed (thus allowing you to free
241 * ** If you are using overwrite mode, ALWAYS **
242 * ** check the return value of this parameter! **
243 * Note: You may pass NULL in this parameter, the
244 * function knows how to cope. If you do this,
245 * however, there will be no way to return a
246 * pointer to an old (ie. replaced) node (which is
247 * a problem if you are using overwrite mode).
249 * Output: a boolean value indicating success or failure. The function
250 * will return FALSE if the node could not be added to the tree.
251 * Such failure will only occur if duplicates are not allowed,
252 * nodes cannot be overwritten, AND a duplicate key was found
254 * ------------------------------------------------------------------------ **
257 ubi_btNodePtr OtherP
;
262 if( ubi_btInsert( RootPtr
, NewNode
, ItemPtr
, OldNode
) )
264 RootPtr
->root
= Splay( NewNode
);
265 return( ubi_trTRUE
);
268 /* Splay the unreplacable, duplicate keyed, unique, old node. */
269 RootPtr
->root
= Splay( (*OldNode
) );
270 return( ubi_trFALSE
);
271 } /* ubi_sptInsert */
273 ubi_btNodePtr
ubi_sptRemove( ubi_btRootPtr RootPtr
, ubi_btNodePtr DeadNode
)
274 /* ------------------------------------------------------------------------ **
275 * This function removes the indicated node from the tree.
277 * Input: RootPtr - A pointer to the header of the tree that contains
278 * the node to be removed.
279 * DeadNode - A pointer to the node that will be removed.
281 * Output: This function returns a pointer to the node that was removed
282 * from the tree (ie. the same as DeadNode).
284 * Note: The node MUST be in the tree indicated by RootPtr. If not,
285 * strange and evil things will happen to your trees.
286 * ------------------------------------------------------------------------ **
291 (void)Splay( DeadNode
); /* Move dead node to root. */
292 if( (p
= DeadNode
->Link
[LEFT
]) ) /* If left subtree exists... */
294 ubi_btNodePtr q
= DeadNode
->Link
[RIGHT
];
296 p
->Link
[PARENT
] = NULL
; /* Left subtree node becomes root.*/
298 p
= ubi_btLast( p
); /* Find rightmost left tree node..*/
299 p
->Link
[RIGHT
] = q
; /* ...attach right tree. */
302 RootPtr
->root
= Splay( p
); /* Resplay at p. */
306 if( (p
= DeadNode
->Link
[RIGHT
]) ) /* No left, but right subtree... */
308 p
->Link
[PARENT
] = NULL
; /* Right subtree root becomes... */
309 p
->gender
= PARENT
; /* ...overall tree root. */
313 RootPtr
->root
= NULL
; /* No subtrees => empty tree. */
316 (RootPtr
->count
)--; /* Decrement node count. */
317 return( DeadNode
); /* Return pointer to pruned node. */
318 } /* ubi_sptRemove */
320 ubi_btNodePtr
ubi_sptLocate( ubi_btRootPtr RootPtr
,
321 ubi_btItemPtr FindMe
,
322 ubi_trCompOps CompOp
)
323 /* ------------------------------------------------------------------------ **
324 * The purpose of ubi_btLocate() is to find a node or set of nodes given
325 * a target value and a "comparison operator". The Locate() function is
326 * more flexible and (in the case of trees that may contain dupicate keys)
327 * more precise than the ubi_btFind() function. The latter is faster,
328 * but it only searches for exact matches and, if the tree contains
329 * duplicates, Find() may return a pointer to any one of the duplicate-
333 * RootPtr - A pointer to the header of the tree to be searched.
334 * FindMe - An ubi_btItemPtr that indicates the key for which to
336 * CompOp - One of the following:
337 * CompOp Return a pointer to the node with
338 * ------ ---------------------------------
339 * ubi_trLT - the last key value that is less
341 * ubi_trLE - the first key matching FindMe, or
342 * the last key that is less than
344 * ubi_trEQ - the first key matching FindMe.
345 * ubi_trGE - the first key matching FindMe, or the
346 * first key greater than FindMe.
347 * ubi_trGT - the first key greater than FindMe.
349 * A pointer to the node matching the criteria listed above under
350 * CompOp, or NULL if no node matched the criteria.
353 * In the case of trees with duplicate keys, Locate() will behave as
357 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
361 * That is, when returning a pointer to a node with a key that is LESS
362 * THAN the target key (FindMe), Locate() will return a pointer to the
363 * LAST matching node.
364 * When returning a pointer to a node with a key that is GREATER
365 * THAN the target key (FindMe), Locate() will return a pointer to the
366 * FIRST matching node.
368 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
369 * ------------------------------------------------------------------------ **
374 p
= ubi_btLocate( RootPtr
, FindMe
, CompOp
);
376 RootPtr
->root
= Splay( p
);
378 } /* ubi_sptLocate */
380 ubi_btNodePtr
ubi_sptFind( ubi_btRootPtr RootPtr
,
381 ubi_btItemPtr FindMe
)
382 /* ------------------------------------------------------------------------ **
383 * This function performs a non-recursive search of a tree for any node
384 * matching a specific key.
387 * RootPtr - a pointer to the header of the tree to be searched.
388 * FindMe - a pointer to the key value for which to search.
391 * A pointer to a node with a key that matches the key indicated by
392 * FindMe, or NULL if no such node was found.
394 * Note: In a tree that allows duplicates, the pointer returned *might
395 * not* point to the (sequentially) first occurance of the
396 * desired key. In such a tree, it may be more useful to use
398 * ------------------------------------------------------------------------ **
403 p
= ubi_btFind( RootPtr
, FindMe
);
405 RootPtr
->root
= Splay( p
);
409 void ubi_sptSplay( ubi_btRootPtr RootPtr
,
410 ubi_btNodePtr SplayMe
)
411 /* ------------------------------------------------------------------------ **
412 * This function allows you to splay the tree at a given node, thus moving
413 * the node to the top of the tree.
416 * RootPtr - a pointer to the header of the tree to be splayed.
417 * SplayMe - a pointer to a node within the tree. This will become
421 * Notes: This is an uncharacteristic function for this group of modules
422 * in that it provides access to the internal balancing routines,
423 * which would normally be hidden.
424 * Splaying the tree will not damage it (assuming that I've done
425 * *my* job), but there is overhead involved. I don't recommend
426 * that you use this function unless you understand the underlying
427 * Splay Tree principles involved.
428 * ------------------------------------------------------------------------ **
431 RootPtr
->root
= Splay( SplayMe
);
434 int ubi_sptModuleID( int size
, char *list
[] )
435 /* ------------------------------------------------------------------------ **
436 * Returns a set of strings that identify the module.
438 * Input: size - The number of elements in the array <list>.
439 * list - An array of pointers of type (char *). This array
440 * should, initially, be empty. This function will fill
441 * in the array with pointers to strings.
442 * Output: The number of elements of <list> that were used. If this value
443 * is less than <size>, the values of the remaining elements are
446 * Notes: Please keep in mind that the pointers returned indicate strings
447 * stored in static memory. Don't free() them, don't write over
448 * them, etc. Just read them.
449 * ------------------------------------------------------------------------ **
456 return( 1 + ubi_btModuleID( --size
, &(list
[1]) ) );
460 } /* ubi_sptModuleID */
462 /* ================================ The End ================================= */