如何使用链接列表搜索信息 [英] How do I search info using linklist

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

问题描述

首先,这个问题来自我的作业。在作业1中,我使用数组将4个文件中的信息存储到适当的结构/类中。

在作业2中,我只需要使用链接列表执行相同的操作。



麻烦在于Asg1我搜索了文件1中的特定信息(比如用户输入的ID),并使用文件2中的ID搜索相关信息(ID,名称,年龄)等)。

现在使用数组做的非常简单,但我如何使用link-list来完成此操作。我理解链接列表的基本 - 中等概念。



任何理论或代码等解决方案都将受到赞赏。



我尝试过:



谷歌搜索链接列表的概念。无法找到任何相关信息。

解决方案

要搜索链接列表,您必须遍历列表。这是一段将遍历列表的代码片段。它假定列表指针指向列表的头部,并且有一个方法来获取指向列表中下一个条目的指针。

 ListItem * p = pList; 
while (p)
{
// 在这里您将p的数据与您要搜索的项目进行比较

p = p-> Next();
}

通常,列表的每个条目都有一个指向下一个条目(链接)的指针,因此Next方法只返回该方法,或者您可以更改它以指定指针最佳。如果您的比较找到匹配,那么您有一个指向要使用的列表项的指针。常见的做法是创建搜索功能以在列表中查找文本字符串。下面是一个示例,其中ListItem具有指向文本字符串的指针,指向下一个项目的指针称为pNext:

 ListItem * FindText(ListItem * pList, const   char  * txt)
{
ListItem * p = pList;
while (p)
{
if (strcmp(p - > Text,txt)== 0
break ; // 发现它停止遍历列表
p = p-> pNext;
}
return p; // 指向具有匹配文本的项目,如果没有,则为null
}


First of, this question comes from my Assignment. In assignment 1 I was to use arrays to store information from 4 files into appropriate structs/classes.
In assignment 2 i need to do the same thing only using link-list this time.

The trouble is in Asg1 I searched for a particular info in File 1(say ID entered by user) and searched for relevant info using that ID in File 2(ID, name, age, etc).
Now using arrays to do is really simple, but how am I to do this using link-list. I understand the basic-moderate concepts of link-lists.

Any solution such as theory or codes would be appreciated.

What I have tried:

Google search on the concept of link-list. Couldn't find any relevant information.

解决方案

To search a linked list you have to traverse the list. Here is a snippet of code that will traverse a list. It assumes the list pointer aims at the head of the list and there is a method to get a pointer to the next entry in the list.

ListItem * p = pList;
while( p )
{
   // here you compare p's data to the item you are searching for

   p = p->Next();
}

Typically each entry of the list has a pointer to the next entry (the link) so the Next method would just return that or you could change it to assign the pointer to p. If your comparison finds a match then you have a pointer to the list item to use. A common thing to do is to make a search function to find a text string in the list. Here's an example of one where the ListItem has a pointer to a text string and the pointer to the next item is called pNext :

ListItem * FindText( ListItem *pList, const char *txt )
{
    ListItem * p = pList;
    while( p )
    {
       if( strcmp( p->Text, txt ) == 0 )
           break;   // found it so stop traversing the list
       p = p->pNext;
    }
    return p;  // points to item with matching text or null if none
}


这篇关于如何使用链接列表搜索信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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