首页 > 解决方案 > 在没有任何导入的队列中搜索对象

问题描述

我有一个 Java 程序,它使用扫描仪输入在我的循环队列中插入值,但我必须创建一个搜索方法而不使用任何导入

例如:

public Projects(String sname, String name, int timeLeft)
Projects p = new Projects("ST1", "Title1", 16);
q.insert(p);
Projects r = new Projects("ST2", "Title1", 16);
q.insert(r);

在我的循环队列中插入元素后,我必须使用允许用户输入搜索条件来搜索字符串sname并显示与sname变量连接的位置的搜索方法。

有什么办法可以做到这一点?

标签: javastringsearchqueue

解决方案


绝对有可能找到并知道特定信息在队列中的位置,您只需要编写搜索功能即可。

在此示例中,名称列表将等于您的队列类

public void search(list head,  string sname)
{
     boolean found = false;
     int pos = 0;
     list current = head;
   while(!found)           
   {
       //iterate through the list looking for the sname
       //for each node you do not find it 
       //if found change found to true.
       pos++;
       if(!found)
            current = current.next; //iterate to next node
       if(current.sname == head.sname)  //if it made it all the way around without finding the node
           break;  //this prevents an infinite loop.
    }
 if(found) //found = true
    //put output of what you need here.
 if(!found) //found = false
    //output not found message.

因为这很可能是一项家庭作业,所以我没有给你完整的答案,你必须在其余部分编程才能完成程序。


推荐阅读