java – LinkedList插入节点后
发布时间:2020-12-15 04:34:10 所属栏目:Java 来源:网络整理
导读:我一直在尝试使用 Java在当前节点之后将节点插入到链表中.我已经能够在当前节点之前获得插入但我不能让它工作: 这是insertNodeBefore的代码.我只是想知道是否有一种方法可以调整它以便能够在当前节点之后插入? // Insert new node nVal to the list before
我一直在尝试使用
Java在当前节点之后将节点插入到链表中.我已经能够在当前节点之前获得插入但我不能让它工作:
这是insertNodeBefore的代码.我只是想知道是否有一种方法可以调整它以便能够在当前节点之后插入? // Insert new node nVal to the list before current node curVal public void insertNodeBefore(E nVal,E curVal) { Node<E> newNode = new Node<E>(nVal); Node<E> curr = head; Node<E> prev = null; if (head.getNodeValue() == curVal) { newNode.setNext(head); head = newNode; return; } // scan until locate node or come to end of list while (curr != null) { // have a match if (curr.getNodeValue() == curVal) { // insert node newNode.setNext(curr); prev.setNext(newNode); break; } else { // advanced curr and prev prev = curr; curr = curr.getNext(); } } } 解决方法
基本上找到节点然后:
>将新节点的下一个设置为等于当前 这样的事情应该有效: public void insertNodeBeAfter(E nVal,E curVal) { Node<E> newNode = new Node<E>(nVal); Node<E> curr = head; // scan until locate node or come to end of list while (curr != null) { // have a match // Replaced == with .equals if (curr.getNodeValue().equals(curVal)) { // insert node newNode.setNext(curr.getNext()); curr.setNext(newNode); break; } else { curr = curr.getNext(); } } } 注意不需要对头部进行不同的处理,因为它不会改变. 注意:如果列表为空或者找不到curVal,例如抛出RuntimeException,则可以非常有趣地处理NOT静默. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |