C++ 使用不带重复键的链表进行顺序搜索
我试图做一个seq搜索,检查重复的键,如果存在,我只需要更新值。但当我尝试使用链表时,我会遇到内存问题 普通代码不必检查重复的键(在代码中注释掉)就可以放置值C++ 使用不带重复键的链表进行顺序搜索,c++,linked-list,C++,Linked List,我试图做一个seq搜索,检查重复的键,如果存在,我只需要更新值。但当我尝试使用链表时,我会遇到内存问题 普通代码不必检查重复的键(在代码中注释掉)就可以放置值 class seqSearch { public: int N; //helper class node class node { public: char key; int val; node *next; node(){ key
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++;
}
你有一些问题
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
设置为当前节点first
应在构造函数中用NULL
初始化定义“内存问题”您得到了哪些错误谢谢。它工作得很好。我已经在构造函数中将node类中的每个元素都初始化为NULL,但不是首先将对象本身初始化为NULL。一旦我这么做了,效果很好。谢谢你的帮助。但是我对代码片段有一些问题:current=newnode(k,v,NULL);N++;如果(last==NULL)first=current;它说电流未定义。我不明白是怎么回事。