java - 在链表中按索引搜索

标签 java linked-list

我创建了自己的 LinkedList,其中包含歌曲对象(标题、艺术家等)。我正在尝试添加一个功能,其中用户输入索引位置,并且有关歌曲的信息显示在该特定索引处。我无法获取索引的位置。目前,每次我运行此程序时,它都无法在索引中找到信息。我不确定我是否需要实现搜索功能,或者我是否只是错误地搜索它。

我目前如何尝试按索引搜索

System.out.print("Enter song index location: ");
int searchIndex = input.nextInt();
for (int i = 0; i < list.size(); i++){
    if ( list.get(i).getValue().equals(searchIndex) ){
            System.out.println(list.get(i).getValue());
            found = true;
    }
}
if ( found != true ){
    System.out.println("Song does not exist.");
}

这是我的 LinkedList 类

public class LinkedList {
private Node first;
private Node last;
public LinkedList(){
    first = null;
    last = null;
}
public boolean isEmpty(){
    return first == null;
}
public int size(){
    int count = 0;
    Node p = first;
    while( p != null ){
        count++;
        p = p.getNext();
    }
    return count;
}
public Node get( int i ){
    Node prev = first;
    for(int j=1; j<=i; j++){
        prev = prev.getNext();
}
    return prev;
}
public String toString(){
    String str = "";
    Node n = first;
    while( n != null ){
        str = str + n.getValue() + " ";
         n = n.getNext();
    }
    return str;
}
public void add( Song c ){
    if( isEmpty() ) {
        first = new Node(c);
        last = first;
    }else{
        Node n = new Node(c);
        last.setNext(n);
        last = n;
    }
}

节点类

public class Node {
private Song song;
private Node next;
public Node( Song s ){
    song = s;
    next = null;
}
public Node( Song s, Node n ){
    song = s;
    next = n;
}
public Node getNext(){
    return next;
}
public void setNext(Node n){
    next = n;
}
public Song getValue(){
    return song;
}
public void setValue( Song s ){
    song = s;
}

最佳答案

考虑到 LinkedList 中的功能,这看起来就是您需要做的全部事情:

System.out.print("Enter song index location: ");
int searchIndex = input.nextInt();
if (searchIndex >= 0 && searchIndex < list.size(){ 
   System.out.println(list.get(searchIndex).getValue());
}
else{
    System.out.println("Song does not exist.");
}

关于java - 在链表中按索引搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690215/

相关文章:

java - 指针如何与 Java 中的原始类型一起使用?

c - 在链表中插入第 n 个元素之后

c++ - 遍历链表以查找字符串

从 C 中的文件创建链表

java - 如何在 Java 中使用 BufferedOutputStream 序列化 HashMap?

java - 如何替换命令模式的静态元素初始化?

java - 有效地找到排序数组中的整数数量

java - 标准差小数位数?

c - 如何让链表的最后一个节点参与冒泡排序?

java - 如何在 MuPDF 中实现页面 curl