简体   繁体   English

删除Java中单链表的节点

[英]Deleting nodes of Singly Linked List in Java

I'm having a problem deleting nodes from singly linked lists in Java.我在从 Java 的单链表中删除节点时遇到问题。 I have a list, which has data of integers, and I need to delete all nodes, whose value can be divided by divided by four.我有一个列表,其中包含整数数据,我需要删除所有节点,其值可以除以四。 I also need to move the head and tail pointers in case either of the head or tail elements are deleted.我还需要移动头部和尾部指针,以防头部或尾部元素被删除。 I wrote method for this, and most of the time it works just like I need it to, but sometimes it throws NullPointerException.我为此编写了方法,大多数时候它就像我需要的那样工作,但有时它会抛出 NullPointerException。 How can I fix it?我该如何解决? Here's my code:这是我的代码:

public void delete(){
            Node temp = head, prev = null;
     
            if (temp != null && temp.data % 4 == 0) 
            {
                head = temp.next;
                temp = head;
            }

            while (temp.next != null) 
            {
               if (temp.data % 4 != 0) {
                   prev = temp;
                   temp = temp.next;
               }
               else {
               prev.next = temp.next;
                temp = prev.next;
               }
            }
            if (tail.data % 4 == 0) {
                tail = prev;
                tail.next = null;
                
            }
        }

while (temp.next != null) : temp may be null. while (temp.next != null) : temp 可能是 null。 And some more small problems.还有一些小问题。

This is due to too much complexity.这是由于过于复杂。

    public void delete() {
        Node prev = null;
        for (Node temp = head; temp != null; temp = temp.next) {
           if (temp.data % 4 == 0) {
               if (prev == null) {
                   head = temp.next;
               } else {
                   prev.next = temp.next;
               }
           } else {
               prev = temp;
           }
        }
        tail = prev;
    }
  • The above sets prev to the valid previous node.以上将prev设置为有效的前一个节点。
  • The deletion considers deletion from head or from prev.next.删除考虑从 head 或 prev.next 删除。
  • The tail is updated to the last element. tail更新到最后一个元素。

in your while condition add one more null check:在您的 while 条件下,再添加一个 null 检查:

while (null.= temp && null != temp.next) while (null.= temp && null != temp.next)

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

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