使用没有重复键的链表进行顺序搜索

时间:2013-04-08 19:47:49

标签: c++ linked-list

我正在尝试进行seq搜索,检查重复键,如果存在,我只需要更新值。但是当我尝试使用链表进行时,我遇到了内存问题。

在不必检查重复键(在代码中注释掉)的情况下放置值的普通代码可以正常工作。

class seqSearch
{
public:
    int N;

    //helper class node
    class node
    {
    public:
        char key;
        int val;
        node *next;

        node(){ key = NULL; val = NULL; next = NULL;}
        node(char k,int v, node *nxt)
        {
            this->key = k;
            this->val = v;
            this->next = nxt;
        }

    };

    node *first;
    seqSearch(){N=0;}
    bool isEmpty(){return first == NULL;}
    int size(){return N;}
    void put(char,int);
    int get(char);
};

void seqSearch::put(char k, int v)
{
    /*
    node *oldfirst = first;
    //first = new node(k,v,oldfirst);
    first = new node;
    first->key = k;
    first->val = v;
    first->next = oldfirst;
    N++;
    */

    for (node *x = first; x!= NULL; x=x->next)
    {
        //node *oldfirst = first;
        //first = new node(k, v, oldfirst);
        if(x->key == k)
        {
            x->val = v; 
            return;
        }
    }
    first = new node(k, v, first); N++;

}

2 个答案:

答案 0 :(得分:0)

你有一些问题。

  1. 制作新节点时,您始终会重置first
  2. 您将first节点的next设置为等于自己,保证您无法查看列表。
  3. 尝试更像这样的事情:

    void seqSearch::put(char k, int v)
    {
        node* last = NULL;
        node* current = NULL;
    
        for (node *x = first; x!= NULL; x=x->next)
        {
            if(x->key == k)
            {
                x->val = v; 
                return;
            }
            last = x;
        }
        current = new node(k, v, NULL); N++;
        if( last == NULL )
            first = current;
        else
            last->next = current;
    }
    

    这:

    1. 将新创建的节点跟踪为当前节点。
    2. 跟踪遍历的最后一个节点,因此可以将next设置为新创建的节点。
    3. 如果没有最后一个节点(例如,我们没有遍历任何节点),则将first设置为当前节点。

答案 1 :(得分:0)

应在构造函数

中使用first初始化

NULL

相关问题