链表的数据-> [java, python, java, python, rust, rust]
:
NodeStr first = new NodeStr("java"); NodeStr second = new NodeStr("python"); NodeStr third = new NodeStr("java"); NodeStr fourth = new NodeStr("python"); NodeStr fifth = new NodeStr("rust"); NodeStr sixth = new NodeStr("rust"); first.setNext(second); second.setNext(third); third.setNext(fourth); fourth.setNext(fifth); fifth.setNext(sixth);
prev表示前一个节点,它初始值为null,temp指向当前节点。
代码如下:
public static void remove(NodeStr firstNode, String key) { NodeStr prev = null; NodeStr temp = firstNode; while (temp != null) { if (temp.getItem().equals(key)) { // 表示当前是第一个节点 if (prev == null) { temp = temp.getNext(); firstNode = temp; } else // 不是第一个节点,且prev是不等于key的节点, prev.next执行temp.next { prev.setNext(temp.getNext()); temp = prev.getNext(); } } else { prev = temp; temp = temp.getNext(); } } System.out.println("遍历剩余元素"); NodeStr p2 = firstNode; while (p2 != null) { System.out.println(p2.getItem()); p2 = p2.getNext(); } }