微调搜索和删除

时间:2013-09-21 22:44:46

标签: c++ performance search

我的Data Structures类的任务是实现一个创建Words的Linked List版本。该类称为WORD,是一个链接的字符列表。所需的操作之一是从另一个WORD中删除一个WORD。例如,

WORD t1("testing");
WORD t2("es");

t1.Remove(t2);

cout<<t1; //Outputs tting

WORD t1("testing");
WORD t2("t");
t1.RemoveAll(t2);
cout<<t1; //Outputs esing

以下两者的代码如下:

//Deletes an entire word from the list
//boolean passed to delete first occurrence of that word
//or all occurrences

void WORD::Delete(WORD & B, bool deleteAll)
{
    alpha_numeric *next, *last_word_start, *prev, *currB;

    bool found = false;
    next = last_word_start = prev = this->head;
    currB = B.head;

    while(next != NULL)
    {
        if(next->symbol == currB->symbol)
        {
            next = next->next;
            currB = currB->next;
        }
        else
        {
            prev = last_word_start;
            last_word_start = last_word_start->next;
            next = last_word_start;
            currB = B.head;
        }

        if(currB == NULL)
        {
            prev->next = next;

            while(last_word_start != next)
            {
                if(last_word_start == this->head)
                {
                    this->head = last_word_start->next;
                }
                alpha_numeric *temp = last_word_start->next;
                delete last_word_start;
                last_word_start = temp;
            }

            if(!deleteAll)
                break;

            currB = B.head;
        }
    }
}

所以我的问题是:

  1. 这个功能的运行时间是多少?我认为最糟糕的情况是O(n ^ 2)

  2. 我可以做些什么来提高效率?

  3. 我开始学习优化等等。在尝试优化这个时,思考过程是什么?主要是尝试将其归结为nlog(n)。

0 个答案:

没有答案