我正在尝试进行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++;
}
答案 0 :(得分:0)
你有一些问题。
first
。first
节点的next
设置为等于自己,保证您无法查看列表。尝试更像这样的事情:
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;
}
这:
next
设置为新创建的节点。first
设置为当前节点。答案 1 :(得分:0)
first
初始化 NULL