繁体   English   中英

如何在Java中使用输入值作为参数删除链表

[英]How to delete linked list with input value as parameter in java

我在删除链接列表时遇到问题,因为它应该具有值作为参数。 因此,如果我没有输入1和5,它仍然会删除链接列表,但会删除链接列表中的最后两个数据。

这是我的代码:

public class Set {

    private static class Node {

        private Integer val;
        private Node next;
    }
    Node node;

    public void remove(Integer val) {

    Node curr = node;

    while (curr.next != null && curr.val != val) {
        curr = curr.next;
    }

    if (curr == node) {
        node = curr.next;
    } else {
        Node curr2 = node;
        while (curr2.next != curr) {
            curr2 = curr2.next;
        }
        curr2.next = curr.next;
    }
    }
  }

public static void main(String[] args) {
    Set A = new Set();
    Set B = new Set();

    A.remove(1);
    A.remove(5);

    B.remove(1);
    B.remove(5);
}

为什么要重新发明轮子...尝试使用标准的Java Collection实现之一。 例如: LinkedList #remove(int index)

#remove(对象对象)

#removeFirstOccurence(对象对象)

如果它不是“确切地”满足您的需求,则可以根据需要扩展它。 而不是从头开始创建自己的类。

尝试使用int / Integer玩一点:

  public static void main(String[] args) {
Integer one = new Integer(1);
Integer two = new Integer(2);
Integer three = new Integer(3);

List<Integer> list = new LinkedList<Integer>();
list.add(one);
list.add(two);
list.add(three);
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(3));

System.out.println("Full list: " + list);

//完整清单:[1、2、3、1、2、3]

list.remove(1);
System.out.println("remove(1) by index -> item on index 1: " + list);

//按索引删除(1)->索引1上的项目:[1、3、1、2、3]

list.remove(one);
System.out.println("remove(one) by object -> item equals to object reference 'one' (first by index): " + list);

//按对象删除(one)-> item等于对象引用“ one”(首先按索引):[3,1,2,3]

list.remove(new Integer(1));
System.out.println("remove(new Integer(1)) by object -> item equals to automatically downcasted Integer with value 1: " + list);

//按对象删除(new Integer(1))-> item等于自动向下转换Integer,值1:[3,2,3]}

为什么要实现自己的链接列表,而不仅仅是使用Collections API中的列表?

您的“集合”类实际上是“列表”类,集合与列表具有不同的行为。

您的列表中没有任何值。

为什么不记得第一次扫描时的前一个节点,而不是再次重新扫描以找到前一个节点。

除此之外,我不清楚实际的问题是什么。 您能否更清楚地了解自己的确切行为以及期望得到的行为?

编辑添加:

即使没有找到匹配的节点,您仍然可以继续执行删除操作-因此,当您对找不到的元素执行删除操作时,列表中的最后一项将被删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM