0

I have a Find function that searches a linked list of strings sequentially. This Find functions finds the string and returns it. I also have a remove function that uses this Find function and removes the string from the linked list. Both of my functions work. However, Im trying to test another way to search the linked list and I am wondering if its possible to do a bisectional search in the linked list. Heres my code:

Find

StringList::StringListNode *StringList::find(const string &s) //basic search function
{
    StringListNode *sp = pTop;   // Search
    while (sp != 0 && sp->data != s)
        sp = sp->pNext;
        return sp;


}

Here is the remove function:

 void StringList::remove(string s)
{

    StringListNode *curr = this->find(s);
    if (curr->pPrev != 0)
    {
        curr->pPrev->pNext = curr->pNext;

    }

    if (curr->pNext != 0)
    {
        curr->pNext->pPrev = curr->pPrev;

    }
    if (pTop == curr)
    {
        pTop = curr->pNext;

    }
    if (pBottom == curr)
    {
        pBottom = curr->pPrev;
    }

Both my functions work perfectly. Im just wondering if anyone could show me an example on how to search the linked list but instead of a sequential search, i would like to see how a bisectional search would work for learning purposes. Any suggestions? Thanks!

WestonBuckeye
  • 45
  • 2
  • 3
  • 11
  • For bisection you need a way to find the "middle" of the sequence quickly. This is possible in O(N) time only for linked lists, unless you introduce some sort of special book-keeping which would make the linked list to something completely different - probably some kind of tree. If search is the operation you want to optimize for, choose different data structure: balanced tree, hash map or similar... – Paul Michalik Jul 17 '13 at 17:44
  • @PaulMichalik Im thinking making a node called `pMiddle` and set it equal to something like `pTop + pBottom / 2`. and have if statements with the value of s. Is there anyway to make this work? – WestonBuckeye Jul 17 '13 at 18:47
  • Having a "pMiddle" means you can optimize the first iteration; then you are back to sequential search. But if you keep other "pMiddle" nodes for each sub-range of the list... then you end up with a skip list. Or a binary search tree. Either way, not a linked list. – DanielKO Jul 17 '13 at 20:45
  • @WestonBuckeye No, not with a simple linked list. `pTop` and `pBottom` are just pointers at some memory location and in order to make your expression yield something meaningful you'd have to put special constraints on the memory locations of `pTop`, `pBottom` and all the nodes in between... – Paul Michalik Jul 18 '13 at 17:37

0 Answers0