TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: FRANK BLACK
from: DARIN MCBRIDE
date: 1998-05-13 08:16:00
subject: searching linked lists

 FB> My program creates a linked list of nodes that contain 
 FB> two elements: a char array and an unsigned long 
 FB> counter. There eventually get to be quite a few nodes 
 FB> in the list, to the tune of around 26 thousand.
Have you thought about a _completely_ different algorithm?  For example, look 
into binary trees.  The only difficulty here comes in iterating (in order) 
through the tree.  (It is possible - we do it in the C++ binary trees.)
The best hint is to take a look at the the C++ template for the rbtree 
(red-black tree).  The object looks like this:
    |
    |
  +---+
  | T |
  +---+
   / \
  /   \
It has three pointers: the back pointer, the left and right.  Anything less 
than T goes to the left, and anything greater than T goes to the right.  For 
example:
tree* insert_tree(tree* root, T new_object)
{
  while (TRUE)
  {
    if (root->object == new_object)
      return root; /* it is already here */
    if (root->object < new_object)
    {
      /* check the left side */
      if (root->left != NULL)
      {
        /* we have something here, go down this side. */
        root = root-> left;
        iterate;
      }
      /* else ... insert it */
      root->left = malloc(sizeof(*root));
      if (NULL == root->left) return NULL; /* woops! */
      /* set up the new object... */
      root->left->back = root;
      root = root->left; /* simplify my typing  */
      root->left = root->right = NULL;
      root->object = new_object;
      return root;
    }
    /* else root->object > new_object... */
    /* excersize for reader: copy the above, except for the right. */
  }
}
This would make each insert take approximately sqrt(n), assuming average 
distribution.  The idea is that each insert does basically a "binary search" 
to find the right place, but there is no moving of data around to insert in 
the right place.
As for the iteration at the end, you need to scan down to the left-most 
object and work up and down the list.  Remember that when you go up, if you 
came up from the left side, you print this one, then you need to go right 
one, and down the left as far as possible.  If you come up from the right 
side, you need to go up one more - since you just went up one, repeat the 
above.  If you go "up to" the root, you're done - if you came from the right.
Hope this helps,
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.