从链接列表中删除元素

时间:2014-10-17 14:50:40

标签: java linked-list

我需要帮助才能通过用户提示从链接列表中删除元素。任何帮助表示赞赏。这是我到目前为止所做的,但它似乎没有用。

public void removeList(LinkedList someList)
{

    System.out.println(someList);
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a String to Delete:");
    String s = input.nextLine();

    for(int i = 0; i < someList.size(); i++)
    {
    if(s.equals(someList))
    {
    someList.remove(s);
    System.out.println(someList.get(i));
    }
}

2 个答案:

答案 0 :(得分:0)

您不需要在此处使用循环。您可以直接调用remove方法。

尝试以下

public void removeList(LinkedList someList) {

    System.out.println(someList);
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a String to Delete:");
    String s = input.nextLine();

    someList.remove(s);
    System.out.println(someList);
}

答案 1 :(得分:0)

以下代码将避免for循环

public void removeList(LinkedList someList)
{      
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a String to Delete:");
    String s = input.nextLine();

    if (someList.contains(s))
        someList.remove(s);
    System.out.println(someList);     
}