使用无重复键的链表进行顺序搜索
sequential search using linked list without duplicate keys
我试图做一个序列搜索,检查重复键,如果存在,我只需要更新值。但是当我尝试使用链表时,就会出现内存问题。
放入值而不必检查重复键(在代码中注释掉)的正常代码工作得很好。
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
应在构造函数中初始化NULL
你有几个问题。
- 你总是重置
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
为当前节点,如果没有最后一个节点(即,我们没有遍历任何节点)。
相关文章:
- 如何按数字顺序插入链表节点?
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- 无法弄清楚如何使用 c++ 中的链表按从 a 到 z 的顺序显示字母
- Sinlge 链表,C++,删除所有和搜索功能的问题
- 这是在传递 int num 时创建搜索函数的正确方法吗?使用链表库
- C++ 双向链表 - 插入同时保持递增顺序
- 快速搜索链表未编译,需要返回语句
- 链表缺少节点并在打印时颠倒顺序
- 双链表中按字母顺序排序的链接
- 搜索链表时出现隔离错误
- 双向链表插入方法实现 - 正在搜索哪个节点
- 在 C++ 中使用链表按字母顺序对字符串进行排序
- 以相反的顺序打印链表的后半部分
- 不太确定如何从这里继续前进.是否使用链表进行搜索
- 按排序顺序将节点插入链表
- 在双向链表中搜索
- 如何使用信号和插槽从qt表单中获取id,然后在链表中搜索它并使用另一个表单显示结果
- 使用c++在链表中搜索操作
- 字母链表顺序不对
- 使用无重复键的链表进行顺序搜索