我正在尝试进行 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++;
}