如何删除链表中的特定节点 [英] How to delete a specific node in a linked list

查看:43
本文介绍了如何删除链表中的特定节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前需要调试我的deleteNode方法的帮助.它现在可以工作(更新的版本在下面发布),但是我希望它提供必须删除头节点的情况.此刻,它返回NullPointerException,我在其中将 * 插入了deleteNode.我不知道那时我的任何变量如何可以为null,因为我的while循环首先需要 position head 都不能为null.

I previously needed help debugging my deleteNode method. It works now (updated version posted below) but I want it to provide for the case when it has to delete the head node. At the moment, it returns a NullPointerException where I've inserted * in deleteNode. I don't know how any of my variables can be null at that point, seeing as my while loop requires both position and head to not be null in the first place.

public class LinkedList
{
private class Node
{
    int item;
    Node link;

    @SuppressWarnings("unused")
    public Node()
    {
        item = Integer.MIN_VALUE;
        link = null;
    }
    public Node(int x, Node p)
    {
        item = x;
        link = p;
    }
}

private Node head;

public LinkedList()
{
    head = null;
}

public boolean deleteNode (int target)
{
    Node position = head;
    boolean isGone = false;

    while(position != null && head != null)
    {
        if(position.link == head && position.link.item == target)
        {
            head = head.link;
            isGone = true;
            return isGone;
        }
    *** else if(position.link.item == target && position.link != head)
        {
            position.link = position.link.link;
            isGone = true;
            return isGone;
        }
        position = position.link;
    }
    return isGone;
}

public void printList()
{
    System.out.println("Your list is: ");
    Node position = head;
    while(position != null)
    {
        System.out.println(position.item + " ");
        position = position.link;
    }
    System.out.println();
}
}

推荐答案

以下是我看到的问题列表:

Here is a list of the problems I see:

  1. 您实际要使用的枚举数 position 永远不会更新.不需要更新的枚举器 counter .

  1. The enumerator you actually want to use, position, is never updated. The enumerator that is updated, counter is not needed.

您实际上从未删除过该节点.为了删除该节点,您需要将前一个节点的链接设置为匹配节点的链接,从而将其从链中删除.

You are never actually removing the node. In order to remove the node, you need to set the previous node's link to the matching node's link, thus removing it out of the chain.

您没有处理特殊情况.如果传递的列表为空会怎样?如果匹配的节点是第一个节点,会发生什么?最后一个节点?

You aren't dealing with special cases. What happens if the list passed is null? What happens if the matching node is the first node? The last node?

您应该从调用函数返回链接列表的开头.在删除链接列表的头节点时,这是必需的.

You should be returning the head of the linked list from the calling function. This is required for when removing the head node of the linked list.

由于这是一个家庭作业问题,请尝试自己解决,但希望这些要点会有所帮助.

Since this is a homework question, try to work it out for yourself but hopefully those points will help.

这篇关于如何删除链表中的特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆