java - 打印出链表的一部分

标签 java search linked-list nodes

所以我有这个充满名字的链表。用户会搜索名字的第一个字母,它会打印出名字以字母开头的节点。当我运行它时,它认为我没有得到任何回应。虽然如果我在循环中插入一些打印行,我会把它们取回来。

这里是:

public String printSection(){
        LinkedListNode current = front;
        String searchedLetter;
        int i = 0;
        String retSec = "The nodes in the list are:\n";

        //Get the input of the name being removed
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the first letter of the section you would like to print out");
        searchedLetter = s.nextLine();

        //while current is not null
        while(current != null){
            //if the data in current starts with the letter entered for searchedLetter
            if(current.getData().startsWith(searchedLetter)){
            //if(current.getData().substring(0,1) == searchedLetter){
                        //Increment the number of the node
                        i++;
                        //Print the node(s)
                        retSec += "Node " + i + " is: " + current.getData() + "\n";
                        //Traverse the list
                        current = current.getNext();
                        System.out.println("You made it here");
            }
        }
        return retSec;
    }
}

这是:(新的工作方法)

public void printSection(){

    LinkedListNode current = front;
    String searchedLetter;
    int i = 0;

    //Get the input of the name being removed
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the first letter of the section you would like to print out");
    searchedLetter = s.nextLine();

    //while current is not null
    while(current != null){
        //if the data in current starts with the letter entered for searchedLetter
        if(current.getData().startsWith(searchedLetter)){
                    //Increment the number of the node
                    i++;
                    //Print the node
                    System.out.println("Node " + i + " is: " + current.getData());
        }
        //Traverse the list
        current = current.getNext();
    }
}

最佳答案

你在这里遇到了一个无限循环。

您只需要一个 while 循环,无论该元素是否以搜索到的字母开头,您都必须跳转到列表中的下一个元素。

因此修改您的 if 语句并删除第二个 while 循环。还要确保始终转到下一个元素。

编辑:更深入地查看您的代码,我意识到您也没有检查您向用户询问的输入。他其实并不局限于单个字符,而是可以输入整行文字。因此,要么修复你给他的解释,要么引入对你输入的验证(如果输入无效,包括一些错误消息)。

关于java - 打印出链表的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830740/

相关文章:

java - CDI环境中的Spring-Data-JPA?

java - 二分查找函数未到达末尾

c - 如何调用以指针数组作为参数的函数?在C中

c - 使用函数为链表创建项目时丢失数据(并添加随机节点)

c - error : request for member 'next' in something not a structure or union. 是什么意思?

Java Swing : Add tabs into JPanels

java - eclipse 中的 classdefnotfound 错误(奇怪)

java - 不确定为什么这个单元测试有效。 Spring ConfigurationContext 更新或创建新对象?

search - 如何在 WP7 上 Hook 硬件搜索按钮

java - 在包含日期的对象列表中搜索