【问题标题】:Printing out a section of a linked list打印出链表的一部分
【发布时间】:2013-11-18 18:59:42
【问题描述】:

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

这里是:

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();
    }
}

【问题讨论】:

  • 问题可能是您对front 的当前声明,所以首先确保一切正常。然后,查看第二个 while 循环是否真的必要。似乎您只需要第一个来检查您是否还没有到达链表的末尾。
  • 您可以将列表转换为 Set,然后使用子集方法。看看这个答案:stackoverflow.com/questions/7228350/…

标签: java search linked-list nodes


【解决方案1】:

您在这里遇到了无限循环。

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

所以重新编写你的 if 语句并删除第二个 while 循环。还要确保总是转到下一个元素。

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

【讨论】:

  • 很好解释,我明白了。感谢您的回答,非常感谢,当计时器到时将被标记为答案。我将在输入中添加限制以及如果节点不以它们给出的字母开头该怎么办。再次感谢 ;) 还更新了代码以显示新方法
  • 很高兴我能帮上忙。祝你学习顺利。但是,最好保留原始代码并单独添加解决方案,以便其他有类似问题的用户可以从中学习。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2022-01-18
  • 2018-04-23
相关资源
最近更新 更多