在链表中搜索 [英] searching in linked list

查看:105
本文介绍了在链表中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的链接列表中搜索的代码,但它不给我正确的结果。请帮助我,我非常担心。

Here is my code for searching in a linked list, but it doesn't give me the correct result. Please help me, i'm very worried about it.

search() {

  char ser[20];
  cout << "enter data to be searched" << endl;
  gets(ser);

  for ( start=head; start->ptr!=NULL; start=start->ptr ) {
    if ( start->info == ser ) {
      cout << "ok" << endl;
      break;
    }
  }
  cout << "not found" << endl;
}

谢谢,
Saima Kanwal Bhutta

Thanks, Saima Kanwal Bhutta

推荐答案

Saima,

首先,欢迎来到论坛,并欢迎精彩,以及计算机编程的富有成果的世界。

Firstly, Welcome to the forums, and welcome also the wonderful, frustrating, and fruitful world of computer programming.

其次,我编辑了您的帖子。如果你现在点击编辑按钮,你会看到如何布局你的源代码,所以论坛很好地显示。

Secondly, I edited your post. If you click the edit button now you'll see how to layout your source-code, so the forum displays it nicely.

第三,我想你的意思是 return ,你说 break ... allways看到未找到消息。这是你想要的吗?

Thirdly, I guess you meant return where you said break ... so that you don't allways see the "not found" message. Is that what you wanted?

第四,我建议你从列表搜索部分分离用户输入部分...它很容易完成, -list-search可用于任何字符串(从任何地方),而不只是用户现在输入的字符串。

Fourthly, I suggest you seperate the user-input part from the list-search part... it's easily done, and it makes the linked-list-search usable with any string (from anywhere), not just one which user enters right now. Likewise seperate the output from the search, that way you can re-use the search later, to produce whatever output is appropriate in the circumstances.

最后,这些变量名称(原谅我)吮吸!

Lastly, Those variable names (forgive me) suck!

所以...我的ANSI-C版本看起来像这样:

So... My ANSI-C version would look something like this:

int contains(char* target) {
  for ( Node node=head; node->next!=NULL; node=node->next ) {
    if ( strcmp(node->data, target)==0 ) {
      return 0; // TRUE
    }
  }
  return 1; // FALSE
}

上面是链表,这有助于使你的代码更加可读,因此可维护。也是WTF是一个伺服...如何目标?

The above are "fairly standard" names for the parts of a linked list, which help to make your code that much more readable, and therefore maintainable. Also WTF is a "ser"... how-about "target"?

如果这一切都在你的头上,那么不要担心它...只是忽略这个建议,现在。

If this is all over your head then don't worry about it... just ignore this advise, for now.

干杯。 Keith。

这篇关于在链表中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆