请高手来帮我找找错误!关于链表的问题

cdab1986 2009-04-28 01:15:26

#include <iostream>
using namespace std;

class linked_list_element
{
public:
int data;
private:
linked_list_element *next_ptr;
friend class linked_list;
};
class linked_list
{
public:
linked_list_element *first_ptr;
linked_list(){first_ptr = 0;}
inline void add_list (int item);
bool find (const int& a);
};

void linked_list::add_list (int item)
{
linked_list_element *new_ptr;
new_ptr = new linked_list_element;
new_ptr -> data = item;
new_ptr -> next_ptr = first_ptr;
first_ptr = new_ptr;
}

bool linked_list::find (const int& a)
{
linked_list_element *current_ptr;
current_ptr = first_ptr;
while ((current_ptr -> data != a) && (current_ptr != 0))
current_ptr = current_ptr->next_ptr;

return (current_ptr != 0);
}

int main()
{
linked_list lis;
lis.add_list(0);
lis.add_list(1);
lis.add_list(2);
lis.add_list(3);
lis.add_list(4);

bool b;
int x = 6; //把"6”改成0到4之间的数就能正常输出。
b = lis.find (x) ;
if(b)
cout<<"1"<<endl;
else
cout<<"2"<<endl;
return 0;
}

这是一个关于链表的程序,在链表中插入5个数,分别是0到4,我再输入一个数,在链表中查找看有没有数和输入的数相等,有就输出1,没有就输出2.
当我把x赋值为0到4之间的数的时候能正常输出,而把x赋值为其他的数时就报错,错误的原因是当current_ptr = NULL时
data CXX0030: 错误: 无法计算表达式的值
next_ptr CXX0030: 错误: 无法计算表达式的值
请高手给出修改意见,(请不要使用其他方法重写程序)
...全文
103 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhanghuayi_xiyou 2009-04-28
  • 打赏
  • 举报
回复
first_ptr 的指针数据没有初始化,这样他的next_ptr在程序里是个随机数,那么编译器比较的时候当然不知道

first_ptr->next_ptr->next_ptr是什么元素了~

next_ptr CXX0030: 错误: 无法计算表达式的值这个解释因该合理把?
cdab1986 2009-04-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 goodname 的回复:]
while ((current_ptr -> data != a) && (current_ptr != 0)) <---这2个判定条件需要倒过来
current_ptr = current_ptr->next_ptr;
[/Quote]
多谢提醒,知道原因了。
lijinfenghust 2009-04-28
  • 打赏
  • 举报
回复

bool linked_list::find (const int& a)
{
linked_list_element *current_ptr;
current_ptr = first_ptr;
while ((current_ptr != 0) && (current_ptr -> data != a))//<-----------这一行有错
current_ptr = current_ptr->next_ptr;

return (current_ptr != 0);
}

cdab1986 2009-04-28
  • 打赏
  • 举报
回复
要用模版就太简单了,我只是想学习一下链表
goodname 2009-04-28
  • 打赏
  • 举报
回复
while ((current_ptr -> data != a) && (current_ptr != 0))<---这2个判定条件需要倒过来
current_ptr = current_ptr->next_ptr;

taodm 2009-04-28
  • 打赏
  • 举报
回复
你能不能学学stl里现成的list呀。

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧