简体   繁体   English

从单个链接列表中删除节点

[英]Removing a node from a singly linked list

I've written a code that should remove a node in a singly linked list. 我写了一个代码,应该删除单链表中的节点。 But it's not working at all, ie it prints the original list without removing anything. 但它根本不起作用,即它打印原始列表而不删除任何内容。 What did I do wrong ? 我做错了什么 ? Assume that a list is not empty! 假设列表不为空!

public void removeNode(int data){
        Node current = head;
        Node previous = null;
        while(current != null && current.data != data){
            previous = current;
            current = current.next;
        }
        previous = current.next;
    }

找到节点时,需要将previous.next设置为current.next。

Just try to set the pointers correctly. 只是尝试正确设置指针。 Like: 喜欢:

public void removeNode(int data) {
    Node current = head;
    Node previous = null;
    while (current != null && current.data != data) {
        previous = current;
        current = current.next;
    }

    if (current != null) {
        previous.next = current.next
    }
}

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

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